我有一个pandas.DataFrame。
library(data.table)
setDT(x)[keystroke == 'ENTER', most_recent_new_enter := sender][,
most_recent_new_enter := shift(zoo::na.locf0(most_recent_new_enter))]
我还有另一个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
我想将df2 ['Price_factor']应用于df1 ['Price']列。我尝试了我的代码,但是没有用。
df2
Year Price_factor
2024 1
2025 0.98
谢谢您的帮助。
答案 0 :(得分:3)
您不需要groupby,而是合并两个表,然后将列相乘。我必须通过删除$符号并使用.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
答案 1 :(得分:2)
使用地图,
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 |