[英]group two dataframes with different sizes in python pandas
我有两个数据框,一个具有这种格式的股票历史价格:
年 | 公司1 | 公司2 |
---|---|---|
1980 | 4.66 | 12.32 |
1981年 | 5.68 | 15.53 |
等有数百列,然后我有一个数据框指定一家公司,它的部门和它的国家。
公司 1 | 工业 | 德国 |
---|---|---|
公司 2 | 消费品 | 我们 |
公司 3 | 工业 | 法国 |
我使用第一个数据框来绘制不同公司随时间变化的价格,但是,我现在想以某种方式将第一个表中的数据与第二个表进行分组,并创建一个单独的数据框,该数据框将具有行业总时间价值的形式, IE。
年 | 工业 | 消费品 | 卫生保健 |
---|---|---|---|
1980 | 50.65 | 42.23 | 25.65 |
1981年 | 55.65 | 43.23 | 26.15 |
谢谢
您可以执行以下操作,假设 df_1 是您的 DataFrame,其中包含每年和公司的股票价格,而 df_2 是您的 DataFrame,其中包含有关公司的信息:
# turn company columns into rows
df_1 = df_1.melt(id_vars='year', var_name='company')
df_1 = df_1.merge(df_2)
# groupby and move industry to columns
output = df_1.groupby(['year', 'industry'])['value'].sum().unstack('industry')
输出:
industry consumer goods industrials
year
1980 12.32 4.66
1981 15.53 5.68
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.