[英]Multiply Two different columns from two different Dataframes with specific condition
[英]multiply two columns from two different pandas dataframes
我有一个 pandas.DataFrame。
df1
Year Class Price EL
2024 PC1 $243 Base
2025 PC1 $215 Base
2024 PC1 $217 EL_1
2025 PC1 $255 EL_1
2024 PC2 $217 Base
2025 PC2 $232 Base
2024 PC2 $265 EL_1
2025 PC2 $215 EL_1
我有另一个 pandas.DataFrame
df2
Year Price_factor
2024 1
2025 0.98
我想将 df2['Price_factor'] 应用于 df1['Price'] 列。 我尝试了我的代码,但没有用。
df3=df1.groupby(['Class','EL'])['Price']*df2['Price_factor]
提前谢谢你的帮助。
您不需要 groupby,而是合并两个表,然后将列相乘。 我必须通过删除 $ .astype(float)
并使用.astype(float)
将原始价格列转换为.astype(float)
,以便能够计算新价格:
import pandas as pdb
# df1 = pd.read_clipboard()
# df2 = pd.read_clipboard()
df3 = df1.merge(df2, how='left', on="Year")
df3['New Price'] = df3['Price'].str[1:].astype(float) *df3['Price_factor']
print(df3)
Year Class Price EL Price_factor New Price
0 2024 PC1 $243 Base 1.00 243.00
1 2025 PC1 $215 Base 0.98 210.70
2 2024 PC1 $217 EL_1 1.00 217.00
3 2025 PC1 $255 EL_1 0.98 249.90
4 2024 PC2 $217 Base 1.00 217.00
5 2025 PC2 $232 Base 0.98 227.36
6 2024 PC2 $265 EL_1 1.00 265.00
7 2025 PC2 $215 EL_1 0.98 210.7
使用地图,
df1['Price_factor'] = df1['Year'].map(df2.set_index('Year')['Price_factor'])
df1['Price_adjusted']= df1['Price'].str.strip('$').astype(int) * df1['Price_factor']
df1
输出:
| | Year | Class | Price | EL | Price_factor | Price_adjusted |
|----|--------|---------|---------|------|----------------|------------------|
| 0 | 2024 | PC1 | $243 | Base | 1 | 243 |
| 1 | 2025 | PC1 | $215 | Base | 0.98 | 210.7 |
| 2 | 2024 | PC1 | $217 | EL_1 | 1 | 217 |
| 3 | 2025 | PC1 | $255 | EL_1 | 0.98 | 249.9 |
| 4 | 2024 | PC2 | $217 | Base | 1 | 217 |
| 5 | 2025 | PC2 | $232 | Base | 0.98 | 227.36 |
| 6 | 2024 | PC2 | $265 | EL_1 | 1 | 265 |
| 7 | 2025 | PC2 | $215 | EL_1 | 0.98 | 210.7 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.