简体   繁体   English

pandas Dataframes将列名与列值合并

[英]pandas Dataframes merge column names with column values

I have 2 dataframes 我有2个数据帧

df = pd.DataFrame({'Location': [ 'Hawai', 'Torino', 'Paris'],
                  'Time': [2000, 2001,2002],
                    'Value': [1.2, 2.2,3.4]
                   })
df.set_index(['Location','Time'],inplace=True)


df2 = pd.DataFrame({'Country': [ 'US', 'IT', 'FR'],
                'Unit': [ 'USD', 'EUR', 'EUR'],
                  'Location': [ 'Hawai', 'Torino', 'Paris'],
                  '2000': [666, 888,777],
                    '2002': [44,55,66]
                   })
df2.set_index(['Country','Unit','Location'],inplace=True)  

It produces this : 它产生了这个:

               Value
Location Time       
Hawai    2000    1.2
Torino   2001    2.2
Paris    2002    3.4
                       2000  2002
Country Unit Location            
US      USD  Hawai      666    44
IT      EUR  Torino     888    55
FR      EUR  Paris      777    66  

I need to merge them, such as for each country/unit/Location, each column is multiplied by the corresponding value from the first dataframe(given Location and Time) 我需要合并它们,例如对于每个国家/单位/位置,每列乘以第一个数据帧的相应值(给定位置和时间)
So the result should look like 所以结果应该是这样的

                       2000  2002
Country Unit Location            
US      USD  Hawai      799.2    149.6
IT      EUR  Torino     1065.6    187
FR      EUR  Paris      932.4    224.4  

I'm stuck here, thanks for your help 我被困在这里,谢谢你的帮助

Doing with unstack then mul unstack然后mul

df2.columns=df2.columns.astype(int)
s=df.Value.unstack(fill_value=1)
df2.mul(s)
Out[675]: 
                        2000  2001   2002
Country Unit Location                    
US      USD  Hawai     799.2   NaN   44.0
IT      EUR  Torino    888.0   NaN   55.0
FR      EUR  Paris     777.0   NaN  224.4

Base on the comment below 基于以下评论

df2.mul(df.Value.reset_index('Location',drop=True))
Out[683]: 
                         2000  2001   2002
Country Unit Location                     
US      USD  Hawai      799.2   NaN  149.6
IT      EUR  Torino    1065.6   NaN  187.0
FR      EUR  Paris      932.4   NaN  224.4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM