pandas 基于条件将两个不同的 Dataframe 相乘

ovfsdjhp  于 2023-05-27  发布在  其他
关注(0)|答案(2)|浏览(158)

df1:

year   rate 
2022   1.000
2023   1.015
2024   1.049
2025   1.084
2026   1.121
2027   1.158
2028   1.197
2029   1.237
2030   1.278
2031   1.321
2032   1.365

df2:

Name   value  code  portion
A       10     1      2
B       12     2      0

我的要求是:

Name   value  code  portion       2022              2023           .....     2032
A       10     1      2       1.000*(10-2)+2     1.015*(10-2)+2           1.365*(10-2)+2 
B       12     2      0        12                     12                    12
C       20     1      6       1.000*(20-6)+6     1.015*(20-6)+6           1.365*(20-6)+6
D       8      2      0        8                     8                       8

我尝试了.loc,但失败了
我的审判是

df_multiply=df2['value'].apply(lambda x: x * df1['rate'])
eblbsuwk

eblbsuwk1#

您可以使用numpy广播实现计算,并有条件地更改不需要计算的行。

df2[df1['year']] = (df2['value'].sub(df2['portion']).to_numpy() * (df1['rate'].to_numpy()[:, None]) + df2['portion'].to_numpy()[None, :]).T
df2.loc[~df2['Name'].isin(['A', 'C']), df1['year']] = df2['value']
print(df2)

  Name  value  code  portion  2022   2023    2024    2025    2026    2027    2028    2029    2030    2031   2032
0    A     10     1        2  10.0  10.12  10.392  10.672  10.968  11.264  11.576  11.896  12.224  12.568  12.92
1    B     12     2        0  12.0  12.00  12.000  12.000  12.000  12.000  12.000  12.000  12.000  12.000  12.00
2    C     20     1        6  20.0  20.21  20.686  21.176  21.694  22.212  22.758  23.318  23.892  24.494  25.11
3    D      8     2        0   8.0   8.00   8.000   8.000   8.000   8.000   8.000   8.000   8.000   8.000   8.00
gzszwxb4

gzszwxb42#

您可以执行以下操作:

# Calculating the value
df2[df1['year']] = ((df2['value'] - df2['portion'] if df2['portion'] else df2['value']) * df1['rate']) + df2['portion']

df2.loc[~df2['Name'].isin(['A', 'C']), df1['year']] = df2['value']

相关问题