栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我想将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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610760.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号