Skip to main content
 首页 » 编程设计

Python Dataframe-如何对包含年、月、日数据的三个不同列进行分组,并从第四列计算总和

2024年11月01日8bonelee

我的数据框如下:

input_df =  
index  Year  Month  Day  Hour  Minute  GHI 
0     2017      1    1     7      30   100 
1     2017      1    1     8      30   200 
2     2017      1    2     9      30   300 
3     2017      1    2    10      30   400 
4     2017      2    1    11      30   500 
5     2017      2    1    12      30   600 
6     2017      2    2    13      30   700 

我想总结每天的 GHI 数据。从上面我期待如下输出:

result_df =  
    index  Year  Month  Day    GHI 
    0     2017      1    1     300 
    1     2017      1    2     700 
    2     2017      2    1     1100 
    3     2017      2    2     700 

我的代码和我目前的输出是:

result_df = input_df.groupby(['Year','Month','Day'])['GHI'].sum() 
print(result_df) 
result_df =  
    index  Year  Month  Day    GHI 
    0     2017      1    1     1400 
    1     2017      2    2     1400 

我上面的代码结合了每个月的第一天并对数据求和。但这是错误的。如何克服?

请您参考如下方法:

您的尝试非常接近。需要记住的是 pd.groupby() 有一个默认值为 True 的参数 as_index。因此,您的 groupby() 输出一个多索引数据框。要获得所需的输出,您可以在 groupby 之后链接 reset_index() 方法,或者将 as_index 参数的值更改为 False。

result_df = input_df.groupby(['Year','Month','Day'])['GHI'].sum() 
 
result_df 
Out[12]:  
Year  Month  Day 
2017  1      1       300 
             2       700 
      2      1      1100 
             2       700 
Name: GHI, dtype: int64 
 
# Getting the desired output 
input_df.groupby(['Year','Month','Day'])['GHI'].sum().reset_index() 
Out[16]:  
   Year  Month  Day   GHI 
0  2017      1    1   300 
1  2017      1    2   700 
2  2017      2    1  1100 
3  2017      2    2   700 
 
input_df.groupby(['Year','Month','Day'], as_index=False)['GHI'].sum() 
Out[17]:  
   Year  Month  Day   GHI 
0  2017      1    1   300 
1  2017      1    2   700 
2  2017      2    1  1100 
3  2017      2    2   700