我要在熊猫DataFrame中将两列相乘并将结果添加到新列中
我正在尝试将pandas Dataframe(orders_df)中的两个现有列相乘-价格(股票收盘价)和Amount(股票数量),并将计算结果添加到名为“值”的新列中。 由于某种原因,当我运行此代码时,“值”列下的所有行均为正数,而某些行应为负数。 在DataFrame的“操作”列下,有七行带有“出售”字符串,七行带有“购买”字符串。
for i in orders_df.Action:
if i == 'Sell':
orders_df['Value'] = orders_df.Prices*orders_df.Amount
elif i == 'Buy':
orders_df['Value'] = -orders_df.Prices*orders_df.Amount)
请让我知道我做错了!
OAK asked 2020-01-26T20:14:43Z
7个解决方案
71 votes
我认为一个不错的解决方案是使用API docs方法(另请参见API docs):
In [37]: values = df.Prices * df.Amount
In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)
In [39]: df
Out[39]:
Prices Amount Action Values
0 3 57 Sell 171
1 89