python dataframe分组求和,pandas datafram中按特定月份分组和求和值
這里有一個稍微不同的方法:使用year和month來構建索引,然后使用一個UDF groupby()。在
示例數據:N = 10
years = pd.date_range("1981", "2017", freq="A").year
dates = np.random.choice(years, size=N, replace=True)
months = np.random.choice(range(1,13), size=N, replace=True)
inches = np.random.randint(1,20, size=N)
mm = np.random.randint(1,100, size=N)
data = {"year":dates, "month":months, "inch":inches, "mm":mm}
df = pd.DataFrame(data)
df
inch mm month year
0 19 31 12 1990
1 8 71 9 1986
2 5 85 2 2009
3 17 8 12 2005
4 10 14 12 1987
5 7 87 2 1982
6 8 59 2 2004
7 8 74 8 2016
8 5 6 6 1993
9 3 7 12 1982
現在根據年份進行子集并構建索引:
^{pr2}$
然后使用year和月份分隔函數groupby:def month_gb(x):
if x.month in range(3,6):
return 'MAM'
elif x.month in range(6,10):
return 'JJAS'
elif x.month in range(10,13):
return 'OND'
df.loc[mask].groupby(["year", month_gb]).mm.sum()
year
1987 OND 14
1990 OND 31
1993 JJAS 6
2005 OND 8
2016 JJAS 74
Name: mm, dtype: int64
總結
以上是生活随笔為你收集整理的python dataframe分组求和,pandas datafram中按特定月份分组和求和值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mongoose如何发送html页面,M
- 下一篇: android root截图软件下载,截