pandas是一個(gè)方便易用的Python數(shù)據(jù)處理庫(kù),數(shù)據(jù)科學(xué)家們的利器之一哦。
本文簡(jiǎn)要介紹pandas的一些常用方法。
1 語(yǔ)法——?jiǎng)?chuàng)建DataFrames
import pandas as pd
Ex 1.1 由字典創(chuàng)建DataFrames
df = pd.DataFrame(
{"a":[4,5,6], #每一列的數(shù)據(jù)
"b":[7,8,9]},
index = [1,2,3]) #行索引
df

Ex 1.2 由數(shù)組創(chuàng)建DataFrames
df = pd.DataFrame(
[[4,7],
[5,8],
[6,9]],
index = [1,2,3],
columns = ['a','b'])
df

Ex 1.3 多重索引的DataFrames
df = pd.DataFrame(
{"a":[4,5,6],"b":[7,8,9]},
index = pd.MultiIndex.from_tuples(
[('d',1),('d',2),('e',2)]))
df

2 Reshaping Data ——改變數(shù)據(jù)集的布局
Ex 2.1 pd.melt
考慮一個(gè)DataFrame, 某些列為ID變量id_vars,其余列為測(cè)量的變量value_vars; 測(cè)量變量列被逆透視為行,最終除了ID列只剩下兩列variable 和 value。這個(gè)函數(shù)起名為融化melt,名副其實(shí)——將許多列消融至兩列,胖胖表變成瘦瘦表的視覺(jué)效果。
[使用場(chǎng)景]:適合用于將高維特征轉(zhuǎn)化為 Event Log(ID,F(xiàn)eatX,x)
df = pd.DataFrame(
{"a":[1,2,3],"b":[4,5,6],"c":[7,8,9]},
index = [1,2,3])
df

pd.melt(df,id_vars=['a'])

Ex 2.2 df.pivot
[使用場(chǎng)景]:與melt相反,pivot將行組織成緊湊的列,適合將Event log 轉(zhuǎn)化為 高維特征矩陣。
考慮這么一個(gè)DataFrame
df = pd.DataFrame({'foo': ['one','one','one','two','two','two'],
'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
'baz': [1, 2, 3, 4, 5, 6]})
對(duì)foo列進(jìn)行bar透視,即將foo這一列變成新的行索引,bar這一列變成列索引,這樣我們就可以清晰地看見(jiàn)foo列和bar列的關(guān)系

df.pivot(index = 'foo',columns = 'bar',values = 'baz')

Ex 2.3 pd.concat
向DataFrame中添加行或列
pd.concat([df,df])#注意數(shù)組

pd.concat([df,df],axis = 1)

Ex 2.4 df.unstack
對(duì)于一個(gè)多索引的DataFrame來(lái)說(shuō),我們可以將某一個(gè)層級(jí)的索引“解”出來(lái)——變?yōu)榱小?/p>
df.index.get_level_values(1)
new_df = df[['value']].unstack(level=-1).fillna(False) # level=-1選擇最里面的索引層
new_df.columns = new_df.columns.get_level_values(1) # 取最里層列索引作為新的列
Ex 2.5 Else
- 排序 df.sort_values
- 設(shè)置索引 df.reset_index 將索引置為行號(hào),原索引變成列
- 調(diào)整索引 df.reindex(index=new_index),向原來(lái)的索引中加入或者刪除項(xiàng)
- 重命名列 df.rename
- 丟棄列 df.drop(axis=1)
df

df.sort_values('bar',ascending=False)

df.sort_index()

df.reset_index()

df.rename(columns = {"foo":"conan"})

df.drop(['foo'],axis =1)

3 Subset Observations ——行
- 頭幾行
- 尾幾行
- 去重
- 邏輯準(zhǔn)則
- 采樣
- 按位置選擇
- 按序選擇(最大 最小)

df.head(2)

df.tail(2)

df.drop_duplicates()

df.sample(frac = 0.2)

df.sample(2)

df.iloc[2:3]#與python數(shù)組類似

df.nlargest(2,'baz')

df.nsmallest(2,'baz')

df[df.baz > 1]

4 Subset Variables——列
- 選擇一列
- 選擇多列
- 選擇列名匹配給定正則表達(dá)式的列
- 按位置選列

Ex 4.1 比較 iloc loc ix
- loc 只能處理index的label
- iloc 只能處理index的位置,因此只接受整數(shù)
- ix 試圖像loc一樣通過(guò)label處理index,失敗時(shí)就如同iloc
df.foo
0 one
1 one
2 one
3 two
4 two
5 two
Name: foo, dtype: object
df[['foo','bar']]

df.filter(regex='o$')

df.loc[:,'bar':'foo']

df.iloc[:,[0,1]]

df.loc[df['baz'] > 1, ['foo','bar']]

5 Summarize Data
- 統(tǒng)計(jì)unique值的出現(xiàn)頻率 df.column_name.value_counts()
- 每一列的描述性統(tǒng)計(jì) df.decribe
- 常用summary functions
- 處理各種pandas對(duì)象:DataFrame columns,Series,GroupBy,Expanding,Rolling
- 每個(gè)group得到單獨(dú)的一個(gè)值
- 當(dāng)應(yīng)用到DataFrame時(shí),返回Series
其中apply函數(shù)需要指定axis
* 0 or 'index': apply function to each column
* 1 or 'columns': apply function to each row

df.foo.value_counts()
two 3
one 3
Name: foo, dtype: int64
df.describe()

type(df.sum())
pandas.core.series.Series
df

image.png
def myfunc(row):
#print(row)
#print(type(row))
print(row.foo)
return"finished"
df.apply(myfunc,axis=1)#注意指定axis
one
one
one
two
two
two
0 finished
1 finished
2 finished
3 finished
4 finished
5 finished
dtype: object
6 缺失值
- dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
- fillna
7 創(chuàng)建新變量
- df.assign 給DataFrame添加新的一列,返回一個(gè)新的dataframe
- 也可直接df['new_col']
- pd.qcut(df.col,q,labels,precision)按分位數(shù)離散化數(shù)據(jù)
- df.clip 閾值化
df = df.assign(Area = lambda df:df.bar+df.foo)
df

df['Volumn'] = df.Area + df.foo
df

pd.cut(df.baz,3,retbins=True)#分成3類
(0 (0.995, 2.667]
1 (0.995, 2.667]
2 (2.667, 4.333]
3 (2.667, 4.333]
4 (4.333, 6]
5 (4.333, 6]
Name: baz, dtype: category
Categories (3, object): [(0.995, 2.667] < (2.667, 4.333] < (4.333, 6]],
array([ 0.995 , 2.66666667, 4.33333333, 6. ]))
df.baz.clip(lower=2,upper=3)
0 2
1 2
2 3
3 3
4 3
5 3
Name: baz, dtype: int64
8 Group Data
- df.groupby(by='col')按列分組
- df.groupby(level='ind')按某層級(jí)的索引分組
分組后返回的GroupBy Object
- size 求分組大小
- agg 使用函數(shù)對(duì)小組進(jìn)行聚合
- 上述的summarize函數(shù)
- 應(yīng)用到每個(gè)group,然后返回和原來(lái)的DataFrame一樣大小的DataFrame
- df.shift(1)
- df.shift(-1)
- rank(method='dense')返回排序后的rank值
- rank(method='min')相等值取最小的rank值
- ...
- cumsum
- cummax
- cummin
- cumprod
df

df.groupby('foo').shift(1)#分組,每組都移動(dòng)

df.groupby('foo').rank(method = 'dense')

df.rank(method = 'dense')

df.rank(method = 'min')

df.rank(pct=True)

df.baz.rank(method = 'first')
0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
5 6.0
Name: baz, dtype: float64
9 Windows
- expanding累積窗
- rolling滑動(dòng)窗 moving average curve with variance as shades
df.expanding(2).sum()

df.expanding(1).sum()

df.expanding(3).sum()

image.png
import numpy as np
df = pd.DataFrame(np.random.randn(1000,4),
index = pd.date_range('1/1/2000', periods=1000),
columns = ['A', 'B', 'C', 'D'])
df = df.cumsum()
df.rolling(window=60).sum().plot(subplots=True)
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fadbc4c5b70>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7fadbc441e10>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7fada8c15ef0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7fada8bea048>], dtype=object)
import matplotlib.pyplot as plt
plt.show()

10 繪圖
df.plot.hist()
<matplotlib.axes._subplots.AxesSubplot at 0x7fada8a66518>
plt.show()

df.plot.scatter(x='A',y='B')
<matplotlib.axes._subplots.AxesSubplot at 0x7fada8905240>
plt.show()

11 Combine Data Sets
- Join pd.merge(df1,df2,how='inner',on='key')
- 過(guò)濾 df1[~df1.x1.isin(df2.x1)]
- 集合操作
