Pandas是一個開源的Python數據分析庫。Pandas把結構化數據分爲了三類:html
DataFrame較爲常見,所以本文主要討論內容將爲DataFrame。DataFrame的生成可經過讀取純文本、Json等數據來生成,亦能夠經過Python對象來生成:python
import pandas as pd import numpy as np df = 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,咱們能夠看到其固有屬性:sql
# data type of columns df.dtypes # indexes df.index # return pandas.Index df.columns # each row, return array[array] df.values # a tuple representing the dimensionality of df df.shape
官方Doc給出了部分SQL的Pandas實現,在此基礎上本文給出了一些擴充說明。如下內容基於Python 2.7 + Pandas 0.18.1的版本。微信
SQL中的select是根據列的名稱來選取;Pandas則更爲靈活,不但可根據列名稱選取,還能夠根據列所在的position選取。相關函數以下:app
df.loc[1:3, ['total_bill', 'tip']] df.loc[1:3, 'tip': 'total_bill'] df.iloc[1:3, [1, 2]] df.iloc[1:3, 1: 3]
df.at[3, 'tip'] df.iat[3, 1]
df.ix[1:3, [1, 2]] df.ix[1:3, ['total_bill', 'tip']]
此外,有更爲簡潔的行/列選取方式:函數
df[1: 3] df[['total_bill', 'tip']] # df[1:2, ['total_bill', 'tip']] # TypeError: unhashable type
Pandas實現where filter,較爲經常使用的辦法爲df[df[colunm] boolean expr]
,好比:設計
df[df['sex'] == 'Female'] df[df['total_bill'] > 20] # or df.query('total_bill > 20')
在where子句中經常會搭配and, or, in, not關鍵詞,Pandas中也有對應的實現:code
# and df[(df['sex'] == 'Female') & (df['total_bill'] > 20)] # or df[(df['sex'] == 'Female') | (df['total_bill'] > 20)] # in df[df['total_bill'].isin([21.01, 23.68, 24.59])] # not df[-(df['sex'] == 'Male')] df[-df['total_bill'].isin([21.01, 23.68, 24.59])] # string function df = df[(-df['app'].isin(sys_app)) & (-df.app.str.contains('^微信\d+$'))]
對where條件篩選後只有一行的dataframe取其中某一列的值,其兩種實現方式以下:htm
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')
drop_duplicates根據某列對dataframe進行去重:對象
df.drop_duplicates(subset=['sex'], keep='first', inplace=True)
包含參數:
group通常會配合合計函數(Aggregate functions)使用,好比:count、avg等。Pandas對合計函數的支持有限,有count和size函數實現SQL的count:
df.groupby('sex').size() df.groupby('sex').count() df.groupby('sex')['tip'].count()
對於多合計函數,
select sex, max(tip), sum(total_bill) as total from tips_tb group by sex;
實如今agg()中指定dict:
df.groupby('sex').agg({'tip': np.max, 'total_bill': np.sum}) # count(distinct **) df.groupby('tip').agg({'sex': pd.Series.nunique})
SQL中使用as修改列的別名,Pandas也支持這種修改:
# first implementation df.columns = ['total', 'pit', 'xes'] # second implementation df.rename(columns={'total_bill': 'total', 'tip': 'pit', 'sex': 'xes'}, inplace=True)
其中,第一種方法的修改是有問題的,由於其是按照列position逐一替換的。所以,我推薦第二種方法。
Pandas中join的實現也有兩種:
# 1. df.join(df2, how='left'...) # 2. pd.merge(df1, df2, how='left', left_on='app', right_on='app')
第一種方法是按DataFrame的index進行join的,而第二種方法纔是按on指定的列作join。Pandas知足left、right、inner、full outer四種join方式。
Pandas中支持多列order,並能夠調整不一樣列的升序/降序,有更高的排序自由度:
df.sort_values(['total_bill', 'tip'], ascending=[False, True])
對於全局的top:
df.nlargest(3, columns=['total_bill'])
對於分組top,MySQL的實現(採用自join的方式):
select a.sex, a.tip from tips_tb a where ( select count(*) from tips_tb b where b.sex = a.sex and b.tip > a.tip ) < 2 order by a.sex, a.tip desc;
Pandas的等價實現,思路與上相似:
# 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函數提供對dataframe全局修改,亦可經過where條件進行過濾修改(搭配loc):
# overall replace df.replace(to_replace='Female', value='Sansa', inplace=True) # dict replace df.replace({'sex': {'Female': 'Sansa', 'Male': 'Leone'}}, inplace=True) # replace on where condition df.loc[df.sex == 'Male', 'sex'] = 'Leone'
除了上述SQL操做外,Pandas提供對每列/每一元素作自定義操做,爲此而設計如下三個函數:
df['tip'].map(lambda x: x - 1) df[['total_bill', 'tip']].apply(sum) df.applymap(lambda x: x.upper() if type(x) is str else x)
現有兩個月APP的UV數據,要獲得月UV環比增加;該操做等價於兩個Dataframe left join後按指定列作減操做:
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)
對於給定的列,一個Dataframe過濾另外一個Dataframe該列的值;至關於集合的差集操做:
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