Python 将两个不同数据帧中的两列相乘
我有一个熊猫数据框Python 将两个不同数据帧中的两列相乘,python,pandas,dataframe,Python,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
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
我有另一个数据框
df2
Year Price_factor
2024 1
2025 0.98
我想将df2['Price\u factor']应用于df1['Price']列。我尝试了我的代码,但没有成功
df3=df1.groupby(['Class','EL'])['Price']*df2['Price_factor]
提前感谢您的帮助。您不需要groupby,而是将两个表合并,然后将列相乘。我必须通过删除$符号并使用.astypefloat将原始价格列转换为浮动,以便能够计算新价格:
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)
您不需要groupby,而是将两个表合并,然后将列相乘。我必须通过删除$符号并使用.astypefloat将原始价格列转换为浮动,以便能够计算新价格:
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)
使用地图
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 |
使用地图
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 |