我想将pandas DataFrame中的两列相乘并将结果添加到新列中

我想将pandas DataFrame中的两列相乘并将结果添加到新列中,第1张

我想将pandas DataFrame中的两列相乘并将结果添加到新列中

如果我们愿意牺牲海顿解决方案简洁性,则还可以执行以下 *** 作:

In [22]: orders_df['C'] = orders_df.Action.apply(    lambda x: (1 if x == 'Sell' else -1))In [23]: orders_df   # New column C represents the sign of the transactionOut[23]:   Prices  Amount Action  C0       3      57   Sell  11      89      42   Sell  12      45      70    Buy -13       6      43   Sell  14      60      47   Sell  15      19      16    Buy -16      56      89   Sell  17       3      28    Buy -18      56      69   Sell  19      90      49    Buy -1

现在我们不再需要该

if
声明了。使用
Dataframe.apply()
,我们也消除了
for
循环。正如Hayden所指出的,矢量化运算总是更快。

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.CIn [25]: orders_df   # The resulting dataframeOut[25]:   Prices  Amount Action  C  Value0       3      57   Sell  1    1711      89      42   Sell  1   37382      45      70    Buy -1  -31503       6      43   Sell  1    2584      60      47   Sell  1   28205      19      16    Buy -1   -3046      56      89   Sell  1   49847       3      28    Buy -1    -848      56      69   Sell  1   38649      90      49    Buy -1  -4410

解决方案采用两行代码而不是一行,但更易于阅读。我怀疑计算成本也差不多。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5616884.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存