欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Pandas實(shí)現(xiàn)groupby分組統(tǒng)計(jì)的實(shí)踐

 更新時(shí)間:2022年01月20日 10:56:42   作者:夢(mèng)捷者  
本文主要介紹了Pandas實(shí)現(xiàn)groupby分組統(tǒng)計(jì)的實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

類似SQL:
select city,max(temperature) from city_weather group by city;

groupby:先對(duì)數(shù)據(jù)分組,然后在每個(gè)分組上應(yīng)用聚合函數(shù)、轉(zhuǎn)換函數(shù)

本次演示:
一、分組使用聚合函數(shù)做數(shù)據(jù)統(tǒng)計(jì)
二、遍歷groupby的結(jié)果理解執(zhí)行流程
三、實(shí)例分組探索天氣數(shù)據(jù)

1、創(chuàng)建數(shù)據(jù)和導(dǎo)入包

import pandas as pd
import numpy as np
# 加上這一句,能在jupyter notebook展示matplot圖表
%matplotlib inline

df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
? ? ? ? ? ? ? ? ? ?'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
? ? ? ? ? ? ? ? ? ?'C': np.random.randn(8),
? ? ? ? ? ? ? ? ? ?'D': np.random.randn(8)})

2、分組使用聚合函數(shù)做數(shù)據(jù)統(tǒng)計(jì)

1、單個(gè)列g(shù)roupby,查詢所有數(shù)據(jù)列的統(tǒng)計(jì)

df.groupby('A').sum()

groupby中的’A’變成了數(shù)據(jù)的索引列
因?yàn)橐y(tǒng)計(jì)sum,但B列不是數(shù)字,所以被自動(dòng)忽略掉

2、多個(gè)列g(shù)roupby,查詢所有數(shù)據(jù)列的統(tǒng)計(jì)

df.groupby(['A','B']).mean()

我們看到:(‘A’,‘B’)成對(duì)變成了二級(jí)索引

df.groupby(['A','B'], as_index=False).mean() #這會(huì)使得A、B兩列不會(huì)成為二級(jí)索引

3、同時(shí)查看多種數(shù)據(jù)統(tǒng)計(jì)

df.groupby('A').agg([np.sum, np.mean, np.std])#列變成了多級(jí)索引

4、查看單列的結(jié)果數(shù)據(jù)統(tǒng)計(jì)

# 方法1:預(yù)過(guò)濾,性能更好
df.groupby('A')['C'].agg([np.sum, np.mean, np.std])

# 方法2
df.groupby('A').agg([np.sum, np.mean, np.std])['C']

5、不同列使用不同的聚合函數(shù)

df.groupby('A').agg({"C":np.sum, "D":np.mean})

3、遍歷groupby的結(jié)果理解執(zhí)行流程

for循環(huán)可以直接遍歷每個(gè)group

1、遍歷單個(gè)列聚合的分組

g = df.groupby('A')

for name,group in g:
? ? print(name)
? ? print(group)

可以獲取單個(gè)分組的數(shù)據(jù)

g.get_group('bar')

2、遍歷多個(gè)列聚合的分組

g = df.groupby(['A', 'B'])
for name,group in g:
? ? print(name)
? ? print(group)
? ? print()

name是一個(gè)2個(gè)元素的tuple,代表不同的列

g.get_group(('foo', 'one'))#可以獲取單個(gè)分組的數(shù)據(jù)

可以直接查詢group后的某幾列,生成Series或者子DataFrame

g['C']

for name, group in g['C']:
? ? print(name)
? ? print(group)
? ? print(type(group))
? ? print()

其實(shí)所有的聚合統(tǒng)計(jì),都是在dataframe和series上進(jìn)行的

4、實(shí)例分組探索天氣數(shù)據(jù)

fpath = "./datas/beijing_tianqi/beijing_tianqi_2018.csv"
df = pd.read_csv(fpath)
# 替換掉溫度的后綴℃
df.loc[:, "bWendu"] = df["bWendu"].str.replace("℃", "").astype('int32')
df.loc[:, "yWendu"] = df["yWendu"].str.replace("℃", "").astype('int32')
df.head()
# 新增一列為月份
df['month'] = df['ymd'].str[:7]
df.head()

1、查看每個(gè)月的最高溫度

data = df.groupby('month')['bWendu'].max()
data
data.plot()#繪圖

2、查看每個(gè)月的最高溫度、最低溫度、平均空氣質(zhì)量指數(shù)

group_data = df.groupby('month').agg({"bWendu":np.max, "yWendu":np.min, "aqi":np.mean})
group_data.plot()

到此這篇關(guān)于Pandas實(shí)現(xiàn)groupby分組統(tǒng)計(jì)的實(shí)踐的文章就介紹到這了,更多相關(guān)Pandas groupby分組統(tǒng)計(jì)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論