我有一个时间序列数据,我将其分组,并希望将所有组的数字列相加。
注意:这不是单个组的列的聚合,而是组对象中所有数据帧的相应单元格的总和。
由于它是一个时间序列数据,数据帧中的一些列本质上保持不变,如Region
和Region_Code
,而Time
本身在数据帧中保持不变。
我的伪代码是-
- 按
Region_Code
分组 - 仅选择分组对象的数字列
- 制作区域列表
- 通过迭代区域列表和总和来调用group对象中的数据帧
- 使其他列如
Region
、Region_Code
和Time
但问题是,当我用空数据帧添加被调用的数据帧时,所有内容都变为空/null,所以最终我什么都没有。
import pandas as pd
countries = ['United States','United States','United States','United States','United States', 'Canada', 'Canada', 'Canada', 'Canada', 'Canada', 'China', 'China', 'China', 'China', 'China']
code = ['US', 'US','US','US','US','CAN','CAN','CAN','CAN','CAN', 'CHN','CHN','CHN','CHN','CHN']
time = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
temp = [2.1,2.2,2.3,2.4,2.5, 3.1,3.2,3.3,3.4,3.5, 4.1,4.2,4.3,4.4,4.5]
pressure = [1.0,1.0,1.0,1.0,1.0, 1.1, 1.1, 1.1, 1.1, 1.1, 1.2,1.2,1.2,1.2,1.2]
speed = [20,21,22,23,24, 10,11,12,13,14, 30,31,32,33,34]
df = pd.DataFrame({'Region': countries, 'Time': time, 'Region_Code': code, 'Temperature': temp, 'Pressure': pressure, 'Speed': speed})
countries_grouped = df.groupby('Region_Code')[list(df.columns)[3:]]
country_list = ['US', 'CAN', 'CHN']
temp = pd.DataFrame()
for country in country_list:
temp += countries_grouped.get_group(country) ## <--- Fails
temp
# Had the above worked, the rest of the columns can be made as follows
temp['Region'] = 'All'
temp['Time'] = df['Time']
temp['Region_Code'] = 'ALL'
它看起来并不可怕。最好的方法是什么?
预期输出:
Region Time Region_Code Temperature Pressure Speed
0 All 1 ALL 9.3 3.3 60
1 All 2 ALL 9.6 3.3 63
2 All 3 ALL 9.9 3.3 66
3 All 4 ALL 10.2 3.3 69
4 All 5 ALL 10.5 3.3 72
我认为您需要聚合sum
-默认情况下排除所有非数字列,因此您可以通过DataFrame.reindex
通过原始列添加它们,并通过ALL
:重新查找缺失的值
print (df.groupby('Time', as_index=False).sum())
Time Temperature Pressure Speed
0 1 9.3 3.3 60
1 2 9.6 3.3 63
2 3 9.9 3.3 66
3 4 10.2 3.3 69
4 5 10.5 3.3 72
df = df.groupby('Time', as_index=False).sum().reindex(df.columns, axis=1, fill_value='ALL')
print (df)
Region Time Region_Code Temperature Pressure Speed
0 ALL 1 ALL 9.3 3.3 60
1 ALL 2 ALL 9.6 3.3 63
2 ALL 3 ALL 9.9 3.3 66
3 ALL 4 ALL 10.2 3.3 69
4 ALL 5 ALL 10.5 3.3 72
编辑:对于自定义替换丢失的值,使用DataFrame.fillna
和字典-列名和替换值:
d = {'Region':'GLOBAL','Region_Code':'ALL'}
df1 = df.groupby('Time', as_index=False).sum().reindex(df.columns, axis=1).fillna(d)
print (df1)
Region Time Region_Code Temperature Pressure Speed
0 GLOBAL 1 ALL 9.3 3.3 60
1 GLOBAL 2 ALL 9.6 3.3 63
2 GLOBAL 3 ALL 9.9 3.3 66
3 GLOBAL 4 ALL 10.2 3.3 69
4 GLOBAL 5 ALL 10.5 3.3 72