Dataframe loc - 意外行为

时间:2016-06-16 23:27:41

标签: python pandas dataframe loc

我有一个数据帧df,如下所示:

          Order Type  Quantity

2015-04-30        Buy       200
2015-05-06        Buy       168
2015-05-08       Sell       368
2015-06-04        Buy       126
2015-06-10        Buy       129
2015-06-17       Sell       255
2015-06-18        Buy       126
2015-06-19       Sell       126
2015-11-06        Buy       159
2016-04-01        Buy       218
2016-06-01        Buy       169

我尝试根据订单类型值更改数量列中值的符号(即保持买入为正,卖出为负):

df.loc[df["Order Type"] == "Sell", "Quantity"] *= -1

然而,这会产生意想不到的结果(见第二和第三个卖出价值):

           Order Type  Quantity

2015-04-30        Buy       200
2015-05-06        Buy       168
2015-05-08       Sell      -368
2015-06-04        Buy       126
2015-06-10        Buy       129
2015-06-17       Sell      -368
2015-06-18        Buy       126
2015-06-19       Sell      -368
2015-11-06        Buy       159
2016-04-01        Buy       218
2016-06-01        Buy       169

我可以通过添加额外的列' Sign':

来解决这个问题
df['Sign'] = 1
df.loc[df["Order Type"] == "Sell", "Sign"] = -1
df['Quantity'] *= df['Sign']

但无论如何都想弄明白事情的原因。

0 个答案:

没有答案