我有兩個df,我想在另一個的基礎上操縱一個。我的 df1 看起來像這種日期格式是 mm-dd-yyyy
| 日期 | col_1 | col_2 | col_3 = col_2/col_1 |
|---|---|---|---|
| 2021 年 1 月 1 日 | 100 | 110 | 1.1 |
| 2021 年 2 月 1 日 | 110 | 110 | 1 |
| 2021 年 3 月 1 日 | 120 | 132 | 1.1 |
| 2021 年 4 月 1 日 | 100 | 120 | 1.2 |
現在我的其他資料框看起來像這樣
| 日期 | col_1 | col_2 |
|---|---|---|
| 2021 年 1 月 1 日 | 一種 | 110 |
| 2021 年 1 月 1 日 | 乙 | 110 |
| 2021 年 1 月 1 日 | C | 132 |
| 2021 年 1 月 1 日 | D | 120 |
| 2021 年 2 月 1 日 | 一種 | 110 |
| 2021 年 2 月 1 日 | 乙 | 110 |
| 2021 年 2 月 1 日 | C | 132 |
| 2021 年 3 月 1 日 | D | 120 |
現在我想按日期將 df1 的“col_3”乘以 df2 的“col_2”。請幫忙
我試過這個
def (df1,df2,ind) #ind is integer for month
df2['col_2'] = df2['col_2'] * df1['col_3'].iloc(ind-1)
return df2
我想要的輸出看起來像
| 日期 | col_1 | col_2 |
|---|---|---|
| 2021 年 1 月 1 日 | 一種 | 121 |
| 2021 年 1 月 1 日 | 乙 | 121 |
| 2021 年 1 月 1 日 | C | 145.2 |
| 2021 年 1 月 1 日 | D | 132 |
| 2021 年 2 月 1 日 | 一種 | 110 |
| 2021 年 2 月 1 日 | 乙 | 110 |
| 2021 年 2 月 1 日 | C | 132 |
| 2021 年 3 月 1 日 | D | 132 |
uj5u.com熱心網友回復:
IIUC,使用Date列作為兩個資料框的索引,然后應用您的操作:
df2['col_3'] = df2.set_index('Date')['col_2'] \
.mul(df1.set_index('Date').reindex(df2['Date'])['col_3']).values
print(df2)
# Output
Date col_1 col_2 col_3
0 01/01/2021 A 110 121.0
1 01/01/2021 B 110 121.0
2 01/01/2021 C 132 145.2
3 01/01/2021 D 120 132.0
4 02/01/2021 A 110 110.0
5 02/01/2021 B 110 110.0
6 02/01/2021 C 132 132.0
7 03/01/2021 D 120 132.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429433.html
上一篇:在字典串列中將日期格式從MM/DD/YYYY轉換為YYYY-MM-DDT00:00:00.000Z
下一篇:django.core.exceptions.FieldError:無法將關鍵字“日期”決議為欄位。不允許在“日期”加入
