Python Pandas分組聚合的實現(xiàn)方法
Pycharm 鼠標移動到函數(shù)上,CTRL+Q可以快速查看文檔,CTR+P可以看基本的參數(shù)。
apply(),applymap()和map()
apply()和applymap()是DataFrame的函數(shù),map()是Series的函數(shù)。
apply()的操作對象是DataFrame的一行或者一列數(shù)據(jù),applymap()是DataFrame的每一個元素。map()也是Series中的每一個元素。
apply()對dataframe的內(nèi)容進行批量處理, 這樣要比循環(huán)來得快。如df.apply(func,axis=0,.....) func:定義的函數(shù),axis=0時為對列操作,=1時為對行操作。
map()和python內(nèi)建的沒啥區(qū)別,如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中最為常用和有效的分組函數(shù),有sum()、count()、mean()等統(tǒng)計函數(shù)。
groupby 方法返回的 DataFrameGroupBy 對象實際并不包含數(shù)據(jù)內(nèi)容,它記錄的是df['key1'] 的中間數(shù)據(jù)。當你對分組數(shù)據(jù)應(yīng)用函數(shù)或其他聚合運算時,pandas 再依據(jù) groupby 對象內(nèi)記錄的信息對 df 進行快速分塊運算,并返回結(jié)果。
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() #通過函數(shù)分組
聚合agg()
對于分組的某一列(行)或者多個列(行,axis=0/1),應(yīng)用agg(func)可以對分組后的數(shù)據(jù)應(yīng)用func函數(shù)。例如:用grouped['data1'].agg('mean')也是對分組后的'data1'列求均值。當然也可以同時作用于多個列(行)和使用多個函數(shù)上。
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()常用來處理不同分組的缺失數(shù)據(jù)的填充和top N的計算,會產(chǎn)生層級索引。
而agg可以同時傳入多個函數(shù),作用于不同的列。
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的在這里同樣適用,只是不能傳入多個,這兩個函數(shù)基本是可以通用的。
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功能上基本是相近的,但是多個函數(shù)的時候還是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還能改變返回數(shù)據(jù)的維度。
http://pandas.pydata.org/pandas-docs/stable/groupby.html
此外還有透視表pivot_table ,交叉表crosstab ,但是我沒用過。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺談django開發(fā)者模式中的autoreload是如何實現(xiàn)的
下面小編就為大家?guī)硪黄獪\談django開發(fā)者模式中的autoreload是如何實現(xiàn)的。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
Python使用matplotlib時顯示中文亂碼解決方法(或更改字體)
這篇文章主要給大家介紹了關(guān)于Python使用matplotlib時顯示中文亂碼的解決方法(或更改字體),在Matplotlib中,中文亂碼問題通常出現(xiàn)在圖表的標題、標簽和刻度上,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-12-12
Python如何實現(xiàn)播放本地音樂并在web頁面播放
這篇文章主要為大家詳細介紹了Python如何實現(xiàn)播放本地音樂并在web頁面播放,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2025-02-02
Python第三方庫qrcode或MyQr生成博客地址二維碼
使用第三方庫qrcode或者MyQr給自己的博客網(wǎng)址快速生成二維碼,一鍵分享,文中含有詳細示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
用Python簡單實現(xiàn)個貪吃蛇小游戲(保姆級教程)
本文基于Windows環(huán)境開發(fā),適合Python新手,文中有非常詳細的代碼示例,對正在學習python的小伙伴們很有幫助,需要的朋友可以參考下2021-06-06

