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

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

 更新時(shí)間:2023年06月26日 09:31:21   作者:笑?癮  
在數(shù)據(jù)處理的過(guò)程,有可能需要對(duì)一堆數(shù)據(jù)分組處理,例如對(duì)不同的列進(jìn)行agg聚合操作(mean,min,max等等),下面這篇文章主要給大家介紹了關(guān)于Pandas實(shí)現(xiàn)groupby分組統(tǒng)計(jì)方法的相關(guān)資料,需要的朋友可以參考下

一、如何實(shí)現(xiàn)分組統(tǒng)計(jì)

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

通過(guò)三個(gè)實(shí)例來(lái)了解pandas是如何實(shí)現(xiàn)分組統(tǒng)計(jì)的

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

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

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

導(dǎo)入數(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)})
df

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

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

我們看到:

    groupby中的'A'變成了數(shù)據(jù)的索引列

    因?yàn)橐y(tǒng)計(jì)sum,但B列不是數(shù)字,所以被自動(dòng)忽略掉

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

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

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

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

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

我們看到:列變成了多級(jí)索引

df.groupby('A').agg([np.sum, np.mean, np.std])

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})

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

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

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

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

1.1、可以獲取單個(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'))

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

fpath = "./datas/beijing_tianqi_2018.csv"
df = pd.read_csv(fpath)
# 替換掉溫度的后綴℃
df.loc[:, "bWendu"] = df["bWendu"].str.replace("℃", "").astype('int64')
df.loc[:, "yWendu"] = df["yWendu"].str.replace("℃", "").astype('int64')
df.head()

# 新增一列為月份
df['month'] = df['ymd'].str[:7]
df.head()

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

data = df.groupby('month')['bWendu'].max()
data

type(data)

pandas.core.series.Series

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

df.head()

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

總結(jié)

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

相關(guān)文章

最新評(píng)論