python - 创建一个包含 0,1,0.5 值的列,而不是 pandas 中的 bool 值

标签 python python-3.x pandas

考虑这个数据框:

id   Name   Score   
314  John    100    
345  Sara    200
355  Zack    200
333  Harry    50
334  Chad     50
331  Newton  100

我想根据分数将自定义值分配给新的运算符列,因此如果一个分数小于下一个分数,则为 1;如果大于 0,则为 1;如果保持不变,则为 0.5。这就是我想要的样子:

id   Name   Score  Operator
314  John    100      1
345  Sara    200     0.5
355  Zack    200      0
333  Harry    50     0.5
334  Chad     50      1    
331  Newton  100     NAN

我尝试了差异列和 bool 列的组合,但它没有提供任何摆脱二进制方法的访问权限

最佳答案

首先,设置您的条件:

prev = df.Score.shift(-1)
c1, c2, c3 = df.Score.lt(prev), df.Score.eq(prev), df.Score.gt(prev)

现在使用numpy.select:

out = df.assign(out=np.select([c1, c2, c3], [1, 0.5, 0], np.nan))

    id    Name  Score  out
0  314    John    100  1.0
1  345    Sara    200  0.5
2  355    Zack    200  0.0
3  333   Harry     50  0.5
4  334    Chad     50  1.0
5  331  Newton    100  NaN

这是另一个只是为了好玩的解决方案(仅当差异不小于 0.5 时才有效):

df.Score.diff(-1).mul(-1).add(0.5).clip(0, 1)

0    1.0
1    0.5
2    0.0
3    0.5
4    1.0
5    NaN
Name: Score, dtype: float64

关于python - 创建一个包含 0,1,0.5 值的列,而不是 pandas 中的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705982/

相关文章:

python - extract_image_patches 的类型错误 : unsupported operand type(s) for/: 'NoneType' and 'int' ,

python-3.x - 使用Python打开一个文本文件,对文本文件进行排序然后保存

Python - 从列表中删除标点符号

python - dataframe.describe() 抑制科学记数法

python - 作为新列附加到 Pandas 中的 DataFrame

python - 计算 DataFrame 中每一列的第一个非缺失值

python - 在 Python 中从字符串中获取主题标签的优雅方法?

python - 命名管道不会阻塞

python - PyUSB dev.set_configuration()

python-3.x - 将鼠标悬停在wxpython选项卡上时发生错误