根据Pandas上的列值应用lambda
问题描述:
我有一个数据帧,取决于列Order
的值我想取Value
列的值并做一些计算。根据Pandas上的列值应用lambda
DataFrame1
Order Shares Value
2011-01-10 BUY 1300 340.99
2011-01-10 SELL 1200 340.99
2011-01-11 SELL 1100 330.99
行代码:
impacts['NewValue']=float(impacts.Order.apply(lambda x: (impacts.Value + (impacts.Value * 0.006)) if x == 'SELL' else (impacts.Value - (impacts.Value * 0.006))))
错误:
类型错误:ufunc '乘法' 不包含循环使用签名匹配类型DTYPE(” S32')dtype('S32')dtype('S32')
我的理解是错误是由数字的内容引起的,因此这就是为什么我试图将它转换为浮点数的原因。
预期输出
Order Shares Value NewValue
2011-01-10 BUY 1300 340.99 338.94
2011-01-10 SELL 1200 340.99 343.03
2011-01-11 SELL 1100 330.99 332.97
任何帮助都欢迎。谢谢!
答
希望这有助于:-)(修改自己的代码而已,你的示例代码将返回错误)
df.apply(lambda x: (x.Value + (x.Value * 0.006)) if x.Order == 'SELL' else (x.Value - (x.Value * 0.006)),axis=1)
Out[790]:
2011-01-10 338.94406
2011-01-10 343.03594
2011-01-11 332.97594
dtype: float64
要获得df
df['NewValue']=df.apply(lambda x: (x.Value + (x.Value * 0.006)) if x.Order == 'SELL' else (x.Value - (x.Value * 0.006)),axis=1)
df
Out[792]:
Order Shares Value NewValue
2011-01-10 BUY 1300 340.99 338.94406
2011-01-10 SELL 1200 340.99 343.03594
2011-01-11 SELL 1100 330.99 332.97594
我会用np.where
import numpy as np
np.where(df.Order=='SELL',(df.Value + (df.Value * 0.006)),(df.Value - (df.Value * 0.006)))
Out[794]: array([ 338.94406, 343.03594, 332.97594])
分配完后回
df['NewValue']=np.where(df.Order=='SELL',(df.Value + (df.Value * 0.006)),(df.Value - (df.Value * 0.006)))
df
Out[796]:
Order Shares Value NewValue
2011-01-10 BUY 1300 340.99 338.94406
2011-01-10 SELL 1200 340.99 343.03594
2011-01-11 SELL 1100 330.99 332.97594
答
(太长的评论),这里的温氏np.where
的一个稍微精简版:
i = np.where(df.Order == 'SELL', 1, -1) * 0.006
df.Value = df.Value.mul(i) + df.Value
print(df.Value)
2011-01-10 338.94406
2011-01-10 343.03594
2011-01-11 332.97594
dtype: float64
使用df.Order
确定操作前的征兆。
+1
非常感谢你COLDSPEED。我学到很多东西。 –
你是最棒的,非常感谢你。 –
@Codinghierarchy如果有帮助,你可以接受它:) :) – Wen