Pandas實現(xiàn)groupby分組統(tǒng)計的實踐
類似SQL:
select city,max(temperature) from city_weather group by city;
groupby:先對數(shù)據(jù)分組,然后在每個分組上應用聚合函數(shù)、轉換函數(shù)
本次演示:
一、分組使用聚合函數(shù)做數(shù)據(jù)統(tǒng)計
二、遍歷groupby的結果理解執(zhí)行流程
三、實例分組探索天氣數(shù)據(jù)
1、創(chuàng)建數(shù)據(jù)和導入包
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)計
1、單個列groupby,查詢所有數(shù)據(jù)列的統(tǒng)計
df.groupby('A').sum()groupby中的’A’變成了數(shù)據(jù)的索引列
因為要統(tǒng)計sum,但B列不是數(shù)字,所以被自動忽略掉
2、多個列groupby,查詢所有數(shù)據(jù)列的統(tǒng)計
df.groupby(['A','B']).mean()
我們看到:(‘A’,‘B’)成對變成了二級索引
df.groupby(['A','B'], as_index=False).mean() #這會使得A、B兩列不會成為二級索引
3、同時查看多種數(shù)據(jù)統(tǒng)計
df.groupby('A').agg([np.sum, np.mean, np.std])#列變成了多級索引4、查看單列的結果數(shù)據(jù)統(tǒng)計
# 方法1:預過濾,性能更好
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的結果理解執(zhí)行流程
for循環(huán)可以直接遍歷每個group
1、遍歷單個列聚合的分組
g = df.groupby('A')
for name,group in g:
? ? print(name)
? ? print(group)可以獲取單個分組的數(shù)據(jù)
g.get_group('bar')2、遍歷多個列聚合的分組
g = df.groupby(['A', 'B']) for name,group in g: ? ? print(name) ? ? print(group) ? ? print()
name是一個2個元素的tuple,代表不同的列
g.get_group(('foo', 'one'))#可以獲取單個分組的數(shù)據(jù)可以直接查詢group后的某幾列,生成Series或者子DataFrame
g['C'] for name, group in g['C']: ? ? print(name) ? ? print(group) ? ? print(type(group)) ? ? print()
其實所有的聚合統(tǒng)計,都是在dataframe和series上進行的
4、實例分組探索天氣數(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、查看每個月的最高溫度
data = df.groupby('month')['bWendu'].max()
data
data.plot()#繪圖2、查看每個月的最高溫度、最低溫度、平均空氣質量指數(shù)
group_data = df.groupby('month').agg({"bWendu":np.max, "yWendu":np.min, "aqi":np.mean})
group_data.plot()到此這篇關于Pandas實現(xiàn)groupby分組統(tǒng)計的實踐的文章就介紹到這了,更多相關Pandas groupby分組統(tǒng)計內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python使用matplotlib繪制多個圖形單獨顯示的方法示例
這篇文章主要介紹了Python使用matplotlib繪制多個圖形單獨顯示的方法,結合實例形式分析了matplotlib實現(xiàn)繪制多個圖形單獨顯示的具體操作技巧與注意事項,代碼備有較為詳盡的注釋便于理解,需要的朋友可以參考下2018-03-03

