luc*_*cas 2 python dataframe pandas
我有 2 个数据框:
df1(原始数据大约有 3000 行 x 200 列:190 个加法和乘法,其余还有一些其他信息):
tag A35 A37 A38
ITEM
B1 SAS 8.0 3.0 1.0
B2 HTW 1.0 3.0 3.0
B3 ASD 0.0 8.0 0.0
B4 KLD 1.0 10.0 0.0
Run Code Online (Sandbox Code Playgroud)
df2(行中的“价格”与 df1 中的列相匹配):
day1 day2
prices
A35 1 3
A37 2 2
A38 3 1
Run Code Online (Sandbox Code Playgroud)
我想df1使用方案添加总体 day1_price 和 day2_price 的列:
df1.B1-day1_price = df1.B1_A35 * df2.A35_day1 +
df1.B1_A37 * df2.A37_day1 +
df1.B1_A38 * df2.A38_day1
Run Code Online (Sandbox Code Playgroud)
所以应该是 row1 day1:(b1) = 8*1+3*2+1*3= 17
tag A35 A37 A38 day1_price day2_price
ITEM
B1 SAS 8.0 3.0 1.0 17.0 31.0
B2 HTW 1.0 3.0 3.0 16.0 12.0
B3 ASD 0.0 8.0 0.0 16.0 16.0
B4 ASD 1.0 10.0 0.0 21.0 23.0
Run Code Online (Sandbox Code Playgroud)
因此,我想将列与 中的匹配价格相加和相乘df2。
用于dot乘法join和df1:
#set indices if needed
df1 = df1.set_index("ITEM")
df2 = df2.set_index("prices")
output = df1.join(df1.drop("tag", axis=1).dot(df2).add_suffix("_price"))
>>> output
ITEM tag A35 A37 A38 day1_price day2_price
0 B1 SAS 8 3 1 17 31
1 B2 HTW 1 3 3 16 12
2 B3 ASD 0 8 0 16 16
3 B4 KLD 1 10 0 21 23
Run Code Online (Sandbox Code Playgroud)