0

我有一个数据框 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

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

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']

但无论如何都想弄清楚事情的原因。

4

0 回答 0