python - 添加 groupby 对象的单个数据框的数字列的 Pythonic 方法
问题描述
我有一个我分组的时间序列数据,我想将所有组的数字列加在一起。
注意:这不是单个组列的聚合,而是组对象中所有数据框的相应单元格的总和。
由于它是时间序列数据,因此在数据帧中的几列本质上保持不变,Region
并且Region_Code
其Time
本身在数据帧中保持不变。
我的伪代码是 -
- 通过...分组
Region_Code
- 仅选择分组对象的数字列
- 制作区域列表
- 通过遍历区域列表和求和来调用组对象中的数据框
- 使其他列像
Region
,Region_Code
和Time
但问题是,当我使用空数据框添加被调用的数据框时,一切都变为空/空,所以最终我什么都没有。
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
推荐阅读
- pandas - 熊猫选择匹配多列
- ios - NSDateFormatter dateFromString 崩溃(从 formatter.date 调用(来自:String)
- node.js - socket.io | 我应该将路由处理程序包装在 io.on('connection') 中吗?
- sql - 在 exec 中声明变量会改善 SQL 查询计划吗?
- textinput - 有没有办法将文本添加到 html 中的函数输出?
- c# - 我无法搜索所有 WPF 窗口
- .net - 在 VBA 项目中使用 .NET 散列类
- html - 如何在 Bootstrap 5 中使用带有标题标签的大文本面包屑?
- python - 有没有办法为folium中的每条道路添加工具提示?
- libgit2sharp - 如何使用 LibGit2Sharp 执行 git rebase?