pandas - 从矩阵搜索计算 Pandas 创建数据框
问题描述
我有以下数据框:
df = pd.DataFrame({'Idenitiy': ['Haus1', 'Haus2', 'Haus1','Haus2'],
'kind': ['Gas', 'Gas', 'Strom','Strom'],
'2005':[2,3,5,6],
'2006':[2,3.5,5.5,7]})
不,我希望将以下数据框作为实体产品的输出:
Year Product(Gas) Product(Strom)
2005 6 30
2006 6 38,5
2007 7 38,5
谢谢你。
解决方案
这是一种方法:
# multiply column values
from functools import reduce
def mult(f):
v = [reduce(lambda a,b : a*b, f['2005']), reduce(lambda a,b : a*b, f['2006'])]
return pd.Series(v, index=['2005','2006'])
# groupby and multiply column values
df1 = df.groupby('kind')[['2005','2006']].apply(mult).unstack().reset_index()
df1.columns = ['Year','Kind','vals']
print(df1)
Year Kind vals
0 2005 Gas 6.0
1 2005 Strom 30.0
2 2006 Gas 7.0
3 2006 Strom 38.5
# reshape the table
df1 = (df1
.pivot_table(index='Year', columns=['Kind'], values='vals'))
# fix column names
df1 = df1.add_prefix('Product_')
df1.columns.name = None
df1 = df1.reset_index()
Year Product_Gas Product_Strom
0 2005 6.0 30.0
1 2006 7.0 38.5
推荐阅读
- html - 带有可滚动正文的表格
- python - 用python进行带状图像识别
- node.js - NestJS 未定义的依赖项
- api - .NET Core 3.1 API - 307 临时重定向
- c++11 - c ++ 11如何在使用N个参数调用函数之前检查模板参数包是否有N个参数
- mongodb - Meteor 反应性地将某些字段从用户集合复制到自定义用户配置文件集合
- c# - 如何在 C# 中执行 Visual Studio 命令?
- c# - 坏图像格式异常 C#
- python - 在 Python asyncio 任务中处理未处理的异常后进行整理
- java - 自定义 Android 键盘“Go”不提交 URL 或任何内容?