python - 根据给出 ValueError 的函数创建一个新列

标签 python

我有一个包含两列的数据框:一列包含一个零值和一个值,另一列包含一个数值。

  ZeroOne   Value
    0       10
    1       20
    0       15

目标是创建一个新列,如果 ZeroOne 列包含“0”,则放置值列的值。如果 ZeroOne 值为 1,则新列应为 0。因此,在我的示例中,结果应为:

  ZeroOne   Value   Result
   0        10          10
   1        20           0
   0        15          15

我试过做一个函数:

def function(a,b):
    if a == 1:
        return b
    else:
        return 0

然后做了变量a和b

    a = df['ZeroOne']
    b = df['Value']

在此之后,我添加了一个具有此功能的新列

   df['result'] = function(a,b)

它一直给我值错误:

   The truth value of a Series is ambiguous. Use a.empty, a.bool(), 
   a.item(), a.any() or a.all().

我怎样才能达到我的结果,我做错了什么?

最佳答案

尝试使用 where:

import pandas as pd

df = pd.DataFrame.from_dict({"ZeroOne": [0, 1, 0], "Value": [10, 20, 15]})

df['Result'] = (df['Value'].where(cond=df['ZeroOne'] == 0, other=0))

print(df)

输出:

   Value  ZeroOne  Result
0     10        0      10
1     20        1       0
2     15        0      15

关于python - 根据给出 ValueError 的函数创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56768533/

相关文章:

python - 使用字典的最短路径算法[Python]

python - django,使用 ugettext_lazy 时出现 "is not JSON serializable"?

Python 正则表达式字符串扩展

python - 如何用 pandas 中的字典替换 df 行中的重复项

python - 在 Python 3 中,计算泰语字符的位置

c# - 获取Python可执行文件路径

Python Fabric - 未找到主机。请为连接 : 指定(单个)主机字符串

python - NumPy 的内存效率

python - Jupyterhub-错误 :asyncio:Task exception was never retrieved

python - 在 Python if 语句中使用列表和元组