pandas-5.groupby

pandas的groupby有點(diǎn)像excel的透視表,思路是分類,運(yùn)算,聚合。
一般的表達(dá)為
dataframe.groupby(['列1',‘列2]).mean()
dataframe.groupby(['列1',‘列2]).agg(['函數(shù)1',’函數(shù)2])
多是分組統(tǒng)計(jì)一個(gè)/多個(gè)自有函數(shù),比如mean,max,也可以傳入自定義函數(shù)。

或者
dataframe.groupby(['列1',‘列2])['列名'].apply(function)
多是分組用自定義函數(shù)統(tǒng)計(jì),列名省略則是對(duì)全部dataframe,有則是只對(duì)這一列
或者
dataframe.groupby(['列1',‘列2]).agg({'列1':'函數(shù)1','列2':'函數(shù)2'})
對(duì)多列用不同函數(shù)groupby

其中['列1',‘列2]是分類依據(jù),如果只按一列則直接dataframe.groupby('列1')

groupby是根據(jù)dataframe的行計(jì)算,agg,apply是根據(jù)列計(jì)算。默認(rèn)只對(duì)數(shù)字列進(jìn)行g(shù)roupby。

import tushare as ts
import pandas as pd
code = '000001'
start = '2018-01-15'
end = '2018-01-30'
gf = ts.get_k_data(code, start=start, end=end)
gf = gf.reset_index(drop=True)
gf['label'] = gf['close'].map(lambda x:1 if x > gf['close'].mean() else 2)
code = '000001'
start = '2018-01-15'
end = '2018-01-30'
gf = ts.get_k_data(code, start=start, end=end)
gf = gf.reset_index(drop=True)
gf['label_close'] = gf['close'].map(lambda x:1 if x > gf['close'].mean() else 2)
gf['label_high'] = gf['high'].map(lambda x:1 if x > gf['close'].mean() else 2)

gf1 = gf.groupby('label_close').mean()
gf2 = gf.groupby('label_close').agg(['mean','max'])
gf3 = gf.groupby(['label_close','label_high']).agg(['mean','max'])
gf4 = gf.groupby('label_close')['open'].agg(['mean','max'])
gf5 = gf.groupby('label_close').agg({'open':'mean','high':'max'})

先print(gf)


gf

print(gf1)


gf1

print(gf2)


gf2

print(gf3)


gf3

print(gf4)


gf4

print(gf5)


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容