Pycharm 鼠標移動到函數上,CTRL+Q可以快速查看文檔,CTR+P可以看基本的參數。
apply(),applymap()和map()
apply()和applymap()是DataFrame的函數,map()是Series的函數。
apply()的操作對象是DataFrame的一行或者一列數據,applymap()是DataFrame的每一個元素。map()也是Series中的每一個元素。
apply()對dataframe的內容進行批量處理, 這樣要比循環來得快。如df.apply(func,axis=0,.....) func:定義的函數,axis=0時為對列操作,=1時為對行操作。
map()和python內建的沒啥區別,如df['one'].map(sqrt)。
import numpy as np
from pandas import Series, DataFrame
frame = DataFrame(np.random.randn(4, 3),
columns = list('bde'),
index = ['Utah', 'Ohio', 'Texas', 'Oregon'])
print frame
print np.abs(frame)
print
f = lambda x: x.max() - x.min()
print frame.apply(f)
print frame.apply(f, axis = 1)
def f(x):
return Series([x.min(), x.max()], index = ['min', 'max'])
print frame.apply(f)
print
print 'applymap和map'
_format = lambda x: '%.2f' % x
print frame.applymap(_format)
print frame['e'].map(_format)
Groupby
Groupby是Pandas中最為常用和有效的分組函數,有sum()、count()、mean()等統計函數。
groupby 方法返回的 DataFrameGroupBy 對象實際並不包含數據內容,它記錄的是df['key1'] 的中間數據。當你對分組數據應用函數或其他聚合運算時,pandas 再依據 groupby 對象內記錄的信息對 df 進行快速分塊運算,並返回結果。
df = DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
'key2': ['one', 'two', 'one', 'two', 'one'],
'data1': np.random.randn(5),
'data2': np.random.randn(5)})
grouped = df.groupby(df['key1'])
print grouped.mean()
df.groupby(lambda x:'even' if x%2==0 else 'odd').mean() #通過函數分組
聚合agg()
對於分組的某一列(行)或者多個列(行,axis=0/1),應用agg(func)可以對分組后的數據應用func函數。例如:用grouped['data1'].agg('mean')也是對分組后的’data1’列求均值。當然也可以同時作用於多個列(行)和使用多個函數上。
df = DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
'key2': ['one', 'two', 'one', 'two', 'one'],
'data1': np.random.randn(5),
'data2': np.random.randn(5)})
grouped = df.groupby('key1')
print grouped.agg('mean')
data1 data2
key1
a 0.749117 0.220249
b -0.567971 -0.126922
apply()和agg()功能上差不多,apply()常用來處理不同分組的缺失數據的填充和top N的計算,會產生層級索引。
而agg可以同時傳入多個函數,作用於不同的列。
df = DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
'key2': ['one', 'two', 'one', 'two', 'one'],
'data1': np.random.randn(5),
'data2': np.random.randn(5)})
grouped = df.groupby('key1')
print grouped.agg(['sum','mean'])
print grouped.apply(np.sum) #apply的在這里同樣適用,只是不能傳入多個,這兩個函數基本是可以通用的。
data1 data2
sum mean sum mean
key1
a 2.780273 0.926758 -1.561696 -0.520565
b -0.308320 -0.154160 -1.382162 -0.691081
data1 data2 key1 key2 key1 a 2.780273 -1.561696 aaa onetwoone b -0.308320 -1.382162 bb onetwo
apply和agg功能上基本是相近的,但是多個函數的時候還是agg比較方便。
apply本身的自由度很高,如果分組之后不做聚合操作緊緊是一些觀察的時候,apply就有用武之地了。
print grouped.apply(lambda x: x.describe())
data1 data2
key1
a count 3.000000 3.000000
mean -0.887893 -1.042878
std 0.777515 1.551220
min -1.429440 -2.277311
25% -1.333350 -1.913495
50% -1.237260 -1.549679
75% -0.617119 -0.425661
max 0.003021 0.698357
b count 2.000000 2.000000
mean -0.078983 0.106752
std 0.723929 0.064191
min -0.590879 0.061362
25% -0.334931 0.084057
50% -0.078983 0.106752
75% 0.176964 0.129447
max 0.432912 0.152142
此外apply還能改變返回數據的維度。
http://pandas.pydata.org/pandas-docs/stable/groupby.html
此外還有透視表pivot_table ,交叉表crosstab ,但是我沒用過。
