首页 > 解决方案 > 从矩阵搜索计算 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   

谢谢你。

标签: pandas

解决方案


这是一种方法:

# 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

推荐阅读