【发布时间】: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'] > 0).astype(int)(或者甚至不要打扰,因为True和False是1和0的别名。 -
@Barmar 我已经做了很多研究,但我并没有让我理解它,我不明白为什么在使用 | 时会出现此错误而不是“和”
-
您需要在数据帧的
[]索引中使用它。 -
你知道你可以只用两行代码进行比较吗?
标签: python pandas function numpy