Advanced Python Pandas

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ù)說明:

  1. left 與 right:兩個(gè)不同的 DataFrame
  2. how:指的是合并(連接)的方式有 inner(內(nèi)連接), left(左外連接), right(右外連接), outer(全外連接); 默認(rèn)為 inner
  3. on: 指的是用于連接的列索引名稱。必須存在右右兩個(gè) DataFrame 對(duì)象中,如果沒有指定且其他參數(shù)也未指定則以兩個(gè) DataFrame 的列名交集做為連接鍵
  4. left_on:左則 DataFrame 中用作連接鍵的列名;這個(gè)參數(shù)中左右列名不相同,但代表的含義相同時(shí)非常有用。
  5. right_on:右則 DataFrame 中用作 連接鍵的列名
  6. left_index:使用左則 DataFrame 中的行索引做為連接鍵
  7. right_index:使用右則 DataFrame 中的行索引做為連接鍵
  8. sort:默認(rèn)為 True,將合并的數(shù)據(jù)進(jìn)行排序。在大多數(shù)情況下設(shè)置為 False 可以提高性能
  9. suffixes:字符串值組成的元組,用于指定當(dāng)左右DataFrame存在相同列名時(shí)在列名后面附加的后綴名稱,默認(rèn)為 ('_x','_y')
  10. copy:默認(rèn)為 True,總是將數(shù)據(jù)復(fù)制到數(shù)據(jù)結(jié)構(gòu)中;大多數(shù)情況下設(shè)置為False可以提高性能
  11. indicator:在 0.17.0 中還增加了一個(gè)顯示合并數(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’ 是一個(gè)函數(shù),那么 group 就是 return 的值;frame 是每一個(gè) NAME 后面的 DataFrame。要數(shù)每一個(gè)的個(gè)數(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') or pd.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.

  • 直接進(jìn)行差分,比如求 return:df.diff().

  • Resample: df.resample(rule, fill_method=None, closed=None, label=None). closed/lable: ‘left’ or ‘right’.

  • Example: 歸總求每個(gè)月的均值 df.resample('M').mean().

  • Query with date: df['2016-12'] or df['2016-12':].

  • 重新排列 freq: df.asfreq(freq, method=None). Method=‘bfill’/‘ffill’.

Other

  • 把 DataFrame 里的 a 換成 b:df.replace('a', 'b')
  • 替換 DataFrame 里有一定規(guī)律的字符串:. 代表任意字符; * 代表 0 個(gè)以上重復(fù)字符; + 代表 1 個(gè)以上重復(fù)字符; [] 表示 list 里面出現(xiàn)的都替換掉;具體參見文檔字符串說明
  • Groupby 以后計(jì)數(shù)或求均值等:gourpby('column_A').agg({'column_B': ['size', 'sum'], 'column_C':['count', 'mean', 'max']})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,321評(píng)論 6 543
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,559評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,442評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,835評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,581評(píng)論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,922評(píng)論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,931評(píng)論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,096評(píng)論 0 290
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,639評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,374評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,591評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,104評(píng)論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,789評(píng)論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,196評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,524評(píng)論 1 295
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,322評(píng)論 3 400
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,554評(píng)論 2 379

推薦閱讀更多精彩內(nèi)容