Skip to content Skip to sidebar Skip to footer

Pandas: Bin And Sum

I have the following data (in csv form): Country,City,Year,Value1,Value2 Germany,Berlin,2020,9,3 Germany,Berlin,2017,1,4 Germany,Berlin,2011,1,4 Israel,Tel Aviv, 2007,4.5,1 I woul

Solution 1:

Using pd.cut with groupby

df.groupby([df.Country,df.City,pd.cut(df.Year,[2006,2011,2016,2020]).astype(str)])[['Value1','Value2']].sum().reset_index()
Out[254]: 
   Country      City          Year  Value1  Value2
0  Germany    Berlin  (2006, 2011]     1.0       4
1  Germany    Berlin  (2016, 2020]    10.0       7
2   Israel  Tel Aviv  (2006, 2011]     4.5       1

Post a Comment for "Pandas: Bin And Sum"