python - 根据 Pandas 上的列值应用 lambda

标签 python pandas dataframe conditional-statements

我有一个数据框,根据 Order 列的值,我想获取 Value 列的值并进行一些计算。

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 'multiply' 不包含签名匹配类型 dtype('S32') dtype('S32') dtype('S32') 的循环

我的理解是错误是由数字的内容引起的,因此这就是我尝试将其转换为 float 的原因。

预期输出

            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

关于python - 根据 Pandas 上的列值应用 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780270/

相关文章:

python - 安装requirements.txt错误,语法错误-python2

python - 非浅文件cmp.cmp 究竟做了什么?

python-3.x - Pandas :如何使 value_counts() 超过阈值

python - 来自 Pandas 中两个不同来源的堆叠条形图

r - NA 替换为空格

r - 在大数据帧 (3.2GB) 中使用 sum 非常慢

python - 在python中创建2 '*'的递归幂

python - Pandas:为具有多列的数据框实现groupby +聚合的优雅方法?

python - 基于另一列在列中的单元格上运行函数

python - 使用 OpenCV 为 Otsu 阈值蒙版图像区域