passing functions into another function, resulting in ValueError
I want to create a function than can process my dataframe through two other functions and then create two new columns with the result. But i am stopped by a an error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
i do not know what is going on, as i am using the correct conditional "|"
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().
here is how you can do it in one line:
df['true'], df['true-again'] = (df['a'] >= 0) | (df['b'] >= 0), (df['a'] > 0) | (df['b'] > 0)
print(df)
output:
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