假设我有这样一个df:
client order_type amount
John Buy 100
John Sell 100
Jeff Buy 100
Jeff Buy 100
Aaron Buy 100
Aaron Sell 100
Aaron Buy 100
如果我这样做了:
df.groupby(['client','order_type'])['amount'].sum()
我会得到这样的结果:
John Buy 100
Sell 100
Jeff Buy 100
Sell 100
Aaron Buy 200
Sell 100
如何在新的数据框架中获得类似于买卖列的内容:
Name NetBuy
John 0
Jeff 200
Aaron 100
首先将
sell
值强制转换为负数,然后使用groupby.sum
:只需将您的订单类型映射到一个标志,有很多方法可以做到这一点,但在我看来,最容易阅读的方法是:
输出:
同样的结果使用一个线性和更快的
np.where
:输出:
相关问题 更多 >
编程相关推荐