Pandas是一個(gè)開源的Python數(shù)據(jù)分析庫。Pandas把結(jié)構(gòu)化數(shù)據(jù)分為了三類:
DataFrame較為常見,因此本文主要討論內(nèi)容將為DataFrame。DataFrame的生成可通過讀取純文本、Json等數(shù)據(jù)來生成,亦可以通過Python對象來生成:
import pandas as pdimport numpy as npdf = pd.DataFrame({'total_bill': [16.99, 10.34, 23.68, 23.68, 24.59], 'tip': [1.01, 1.66, 3.50, 3.31, 3.61], 'sex': ['Female', 'Male', 'Male', 'Male', 'Female']})
對于DataFrame,我們可以看到其固有屬性:
# data type of columnsdf.dtypes# indexesdf.index# return pandas.Indexdf.columns# each row, return array[array]df.values# a tuple representing the dimensionality of dfdf.shape
官方Doc給出了部分SQL的Pandas實(shí)現(xiàn),在此基礎(chǔ)上本文給出了一些擴(kuò)充說明。以下內(nèi)容基于Python 2.7 + Pandas 0.18.1的版本。
SQL中的select是根據(jù)列的名稱來選??;Pandas則更為靈活,不但可根據(jù)列名稱選取,還可以根據(jù)列所在的position選取。相關(guān)函數(shù)如下:
print df.loc[1:3, ['total_bill', 'tip']]print df.loc[1:3, 'tip': 'total_bill']print df.iloc[1:3, [1, 2]]print df.iloc[1:3, 1: 3]
print df.at[3, 'tip']print df.iat[3, 1]
print df.ix[1:3, [1, 2]]print df.ix[1:3, ['total_bill', 'tip']]
此外,有更為簡潔的行/列選取方式:
print df[1: 3]print df[['total_bill', 'tip']]# print df[1:2, ['total_bill', 'tip']] # TypeError: unhashable type
Pandas實(shí)現(xiàn)where filter,較為常用的辦法為df[df[colunm] boolean expr]
,比如:
print df[df['sex'] == 'Female']print df[df['total_bill'] > 20]# orprint df.query('total_bill > 20')
在where子句中常常會(huì)搭配and, or, in, not關(guān)鍵詞,Pandas中也有對應(yīng)的實(shí)現(xiàn):
# andprint df[(df['sex'] == 'Female') & (df['total_bill'] > 20)]# orprint df[(df['sex'] == 'Female') | (df['total_bill'] > 20)]# inprint df[df['total_bill'].isin([21.01, 23.68, 24.59])]# notprint df[-(df['sex'] == 'Male')]print df[-df['total_bill'].isin([21.01, 23.68, 24.59])]# string functionprint df = df[(-df['app'].isin(sys_app)) & (-df.app.str.contains('^微信\d+$'))]
對where條件篩選后只有一行的dataframe取其中某一列的值,其兩種實(shí)現(xiàn)方式如下:
total = df.loc[df['tip'] == 1.66, 'total_bill'].values[0]total = df.get_value(df.loc[df['tip'] == 1.66].index.values[0], 'total_bill')
包含參數(shù): group一般會(huì)配合合計(jì)函數(shù)(Aggregate functions)使用,比如:count、avg等。Pandas對合計(jì)函數(shù)的支持有限,有count和size函數(shù)實(shí)現(xiàn)SQL的count: 對于多合計(jì)函數(shù), 實(shí)現(xiàn)在agg()中指定dict: SQL中使用as修改列的別名,Pandas也支持這種修改: 其中,第一種方法的修改是有問題的,因?yàn)槠涫前凑樟衟osition逐一替換的。因此,我推薦第二種方法。 Pandas中join的實(shí)現(xiàn)也有兩種: 第一種方法是按DataFrame的index進(jìn)行join的,而第二種方法才是按on指定的列做join。Pandas滿足left、right、inner、full outer四種join方式。 Pandas中支持多列order,并可以調(diào)整不同列的升序/降序,有更高的排序自由度: 對于全局的top: 對于分組top,MySQL的實(shí)現(xiàn)(采用自join的方式): Pandas的等價(jià)實(shí)現(xiàn),思路與上類似: replace函數(shù)提供對dataframe全局修改,亦可通過where條件進(jìn)行過濾修改(搭配loc): 除了上述SQL操作外,Pandas提供對每列/每一元素做自定義操作,為此而設(shè)計(jì)以下三個(gè)函數(shù): 現(xiàn)有兩個(gè)月APP的UV數(shù)據(jù),要得到月UV環(huán)比增長;該操作等價(jià)于兩個(gè)Dataframe left join后按指定列做減操作: 對于給定的列,一個(gè)Dataframe過濾另一個(gè)Dataframe該列的值;相當(dāng)于集合的差集操作:group
print df.groupby('sex').size()print df.groupby('sex').count()print df.groupby('sex')['tip'].count()
select sex, max(tip), sum(total_bill) as totalfrom tips_tbgroup by sex;
print df.groupby('sex').agg({'tip': np.max, 'total_bill': np.sum})# count(distinct **)print df.groupby('tip').agg({'sex': pd.Series.nunique})
as
# first implementationdf.columns = ['total', 'pit', 'xes']# second implementationdf.rename(columns={'total_bill': 'total', 'tip': 'pit', 'sex': 'xes'}, inplace=True)
join
# 1.df.join(df2, how='left'...)# 2. pd.merge(df1, df2, how='left', left_on='app', right_on='app')
order
print df.sort_values(['total_bill', 'tip'], ascending=[False, True])
top
print df.nlargest(3, columns=['total_bill'])
select a.sex, a.tipfrom tips_tb awhere ( select count(*) from tips_tb b where b.sex = a.sex and b.tip > a.tip) < 2order by a.sex, a.tip desc;
# 1.df.assign(rn=df.sort_values(['total_bill'], ascending=False) .groupby('sex') .cumcount()+1) .query('rn < 3') .sort_values(['sex', 'rn']) # 2.df.assign(rn=df.groupby('sex')['total_bill'] .rank(method='first', ascending=False)) .query('rn < 3') .sort_values(['sex', 'rn'])
replace
# overall replacedf.replace(to_replace='Female', value='Sansa', inplace=True)# dict replacedf.replace({'sex': {'Female': 'Sansa', 'Male': 'Leone'}}, inplace=True)# replace on where condition df.loc[df.sex == 'Male', 'sex'] = 'Leone'
自定義
print df['tip'].map(lambda x: x - 1)print df[['total_bill', 'tip']].apply(sum)print df.applymap(lambda x: x.upper() if type(x) is str else x)
3. 實(shí)戰(zhàn)
環(huán)比增長
def chain(current, last): df1 = pd.read_csv(current, names=['app', 'tag', 'uv'], sep='\t') df2 = pd.read_csv(last, names=['app', 'tag', 'uv'], sep='\t') df3 = pd.merge(df1, df2, how='left', on='app') df3['uv_y'] = df3['uv_y'].map(lambda x: 0.0 if pd.isnull(x) else x) df3['growth'] = df3['uv_x'] - df3['uv_y'] return df3[['app', 'growth', 'uv_x', 'uv_y']].sort_values(by='growth', ascending=False)
差集
def difference(left, right, on): """ difference of two dataframes :param left: left dataframe :param right: right dataframe :param on: join key :return: difference dataframe """ df = pd.merge(left, right, how='left', on=on) left_columns = left.columns col_y = df.columns[left_columns.size] df = df[df[col_y].isnull()] df = df.ix[:, 0:left_columns.size] df.columns = left_columns return df
聯(lián)系客服