Merging DataFrames
語法如下:
merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=True,
suffixes=('_x', '_y'), copy=True, indicator=False)
參數(shù)說明:
- left 與 right:兩個不同的 DataFrame
- how:指的是合并(連接)的方式有 inner(內(nèi)連接), left(左外連接), right(右外連接), outer(全外連接); 默認為 inner
- on: 指的是用于連接的列索引名稱科乎。必須存在右右兩個 DataFrame 對象中掸犬,如果沒有指定且其他參數(shù)也未指定則以兩個 DataFrame 的列名交集做為連接鍵
- left_on:左則 DataFrame 中用作連接鍵的列名;這個參數(shù)中左右列名不相同琳轿,但代表的含義相同時非常有用。
- right_on:右則 DataFrame 中用作 連接鍵的列名
- left_index:使用左則 DataFrame 中的行索引做為連接鍵
- right_index:使用右則 DataFrame 中的行索引做為連接鍵
- sort:默認為 True节榜,將合并的數(shù)據(jù)進行排序。在大多數(shù)情況下設(shè)置為 False 可以提高性能
- suffixes:字符串值組成的元組,用于指定當左右DataFrame存在相同列名時在列名后面附加的后綴名稱室奏,默認為 ('_x','_y')
- copy:默認為 True顺饮,總是將數(shù)據(jù)復(fù)制到數(shù)據(jù)結(jié)構(gòu)中吵聪;大多數(shù)情況下設(shè)置為False可以提高性能
- indicator:在 0.17.0 中還增加了一個顯示合并數(shù)據(jù)中來源情況;如只來自己于左邊(left_only)兼雄、兩者(both)
Idiomatic Pandas: Making Code Pandorable
用連續(xù)的函數(shù)加換行增加代碼的可讀性:
(df.where(df['SUMLEV']==50)
.dropna()
.set_index(['STNAME','CTYNAME'])
.rename(columns={'ESTIMATESBASE2010': 'Estimates Base 2010'}))
注意到吟逝,給 column 重命名的代碼:df.rename(column={'original_name': 'new_name'})
。
Group by
- 遍歷 groupby赦肋,用
for group, frame in df.groupby('NAME’)
块攒,group 是分組的依據(jù)励稳,如果 ’NAME’ 是一個函數(shù),那么 group 就是 return 的值囱井;frame 是每一個 NAME 后面的 DataFrame驹尼。要數(shù)每一個的個數(shù),就用len(frame)
庞呕。 -
groupby(level=0)
, if the axis is a MultiIndex (hierarchical), group by a particular level or levels. -
df.groupby('Category').apply(lambda df,a,b: sum(df[a] * df[b]), 'Weight (oz.)', 'Quantity')
. It uses function on certain column and output after groupby.
Scales
- Ratio scale: units are equally spaced; mathematical operations of +-*/ is valid. e.g. weight and height.
- Interval scale: units are equally spaced; it cannot use operations of * and /. e.g. 1-5 in the questionnaire.
- Ordinal scale: the order of units are important but not evenly spaced. e.g. letter grade A+, A and A-.
- Nominal scale: category of data, but category has no order. e.g. teams of a sport.
-
df['Grades'].astype('category')
, transfer to categorical data. Or,grades = df['Grades'].astype('category', categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'], ordered=True)
, make category in ascending order. -
s = pd.Series([168, 180, 174, 190, 170, 185, 179, 181, 175, 169, 182, 177, 180, 171])
. Use pd.cut to bin this data into 3 bins (we can also label them):pd.cut(s, 3, labels=['Small', 'Medium', 'Large'])
.
Pivot Tables
語法如下:
pivot_table(df, values=, index=, columns=, aggfunc=np.mean, margins=False)
if margins=True
, special All
(default is np.mean) columns and rows will be added with partial group aggregates.
Date Functionality
Timestamp:
pd.Timestamp('9/1/2016 10:05AM')
Period:
pd.Period('1/2016')
orpd.Period('3/5/2016')
Datetime index:
pd.Series(list('abc'), [pd.Timestamp('2016-09-01'), pd.Timestamp('2016-09-02'), pd.Timestamp('2016-09-03')])
output:
2016-09-01 a
2016-09-02 b
2016-09-03 c
dtype: object
- Similarly, period index:
pd.Series(list('def'), [pd.Period('2016-09'), pd.Period('2016-10'), pd.Period('2016-11')])
- Converting to datetime:
pd.to_datetime(arg, dayfirst=False, yearfirst=False)
- Timedeltas:
pd.Timestamp('9/2/2016 8:10AM') + pd.Timedelta('12D 3H')
Working with Dates in Dataframe
Date range:
pd.date_range(start=None, end=None, periods=None, freq=’D’, tz=None, normalize=False, name=None, closed=None)
.freq: (freq aliases in the attachment image)
tz: Time zone name for returning localized DatetimeIndex, for example Asia/Hong_Kong.
closed: Make the interval closed with respect to the given frequency to the ‘left’, ‘right’, or both sides (None).
Example:
dates = pd.date_range('10-01-2016', periods=9, freq='2W-SUN')
查看 index 分別是星期幾:
df.index.weekday_name
.直接進行差分新翎,比如求 return:
df.diff()
.Resample:
df.resample(rule, fill_method=None, closed=None, label=None)
. closed/lable: ‘left’ or ‘right’.Example: 歸總求每個月的均值
df.resample('M').mean()
.Query with date:
df['2016-12']
ordf['2016-12':]
.重新排列 freq:
df.asfreq(freq, method=None)
. Method=‘bfill’/‘ffill’.
Other
- 把 DataFrame 里的 a 換成 b:
df.replace('a', 'b')
- 替換 DataFrame 里有一定規(guī)律的字符串:
.
代表任意字符;*
代表 0 個以上重復(fù)字符住练;+
代表 1 個以上重復(fù)字符料祠;[]
表示 list 里面出現(xiàn)的都替換掉;具體參見文檔字符串說明澎羞。 - Groupby 以后計數(shù)或求均值等:
gourpby('column_A').agg({'column_B': ['size', 'sum'], 'column_C':['count', 'mean', 'max']})