【问题标题】:passing functions into another function, resulting in ValueError将函数传递给另一个函数,导致 ValueError
【发布时间】:2022-01-18 19:16:13
【问题描述】:

我想创建一个函数,它可以通过其他两个函数处理我的数据框,然后用结果创建两个新列。 但是我被一个错误阻止了:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我不知道发生了什么,因为我使用了正确的条件“|”

import pandas as pd
import numpy as np
from numpy.random import randn
np.random.seed(101)

df = pd.DataFrame(randn(9,2),index='1 2 3 4 5 6 7 8 9'.split(),columns='a b'.split())


def bigger_than(df):
        #
        df = df.copy()
        df['a-true'] = np.where(df['a'] > 0, 1, 0)
        df['b-true'] = np.where(df['b'] > 0, 1, 0)
        return df


def less_than(df):
        df = df.copy()
        df['a-true'] = np.where(df['a'] < 0, 1, 0)
        df['b-true'] = np.where(df['b'] < 0, 1, 0)
        return df


def compare(df, func1, func2):
        df = df.copy()
        df['true'] = np.where(func1(df)['a-true'] == 0 | func1(df)['b-true'] == 0, 1, 0)
        df['true-again'] = np.where(func2(df)['a-true'] == 1 | func2(df)['b-true'] == 1, 1, 0)
        return df


print(compare(df, less_than, bigger_than))


Traceback (most recent call last):
  File "C:\Users\jeppe\PycharmProjects\pythonProject3\main.py", line 31, in <module>
    print(compare(df, less_than, bigger_than))
  File "C:\Users\jeppe\PycharmProjects\pythonProject3\main.py", line 26, in compare
    df['true'] = np.where(func1(df)['a-true'] == 0 | func1(df)['b-true'] == 0, 1, 0)
  File "C:\Users\jeppe\PycharmProjects\test\pythonProject3\lib\site-packages\pandas\core\generic.py", line 1537, in __nonzero__
    raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

  • 关于该错误消息的问题有数百个。发帖前你做了哪些研究?
  • 顺便说一句,在这里使用np.where() 是多余且不必要的:只需使用(df_condition).astype(int),例如(df['a'] &gt; 0).astype(int)(或者甚至不要打扰,因为TrueFalse10 的别名。
  • @Barmar 我已经做了很多研究,但我并没有让我理解它,我不明白为什么在使用 | 时会出现此错误而不是“和”
  • 您需要在数据帧的[] 索引中使用它。
  • 你知道你可以只用两行代码进行比较吗?

标签: python pandas function numpy


【解决方案1】:

以下是您如何在一行中做到这一点:

df['true'], df['true-again'] = (df['a'] >= 0) | (df['b'] >= 0), (df['a'] > 0) | (df['b'] > 0)

print(df)

输出:

          a         b   true  true-again
1  1.048158  0.701041   True        True
2  0.835515 -1.614604   True        True
3  2.126922  0.421194   True        True
4 -1.409821 -0.045723  False       False
5 -1.553690  0.825518   True        True
6  0.596085  0.208414   True        True
7 -0.558074 -0.232004  False       False
8 -1.046353  0.737966   True        True
9  0.942001  1.733682   True        True

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2014-01-06
    • 2019-10-09
    • 1970-01-01
    • 2012-09-25
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多