[英]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.