I'm trying to add a column to a pandas dataframe that has a boolean, True for if the number in a different column in the same row is between two values.
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['row1', 'row2', 'row3'],
columns=['a', 'b'])
def add_subtract_list(a, b):
return [a + b, a - b]
df[['sum', 'difference']] = df.apply(
lambda row: add_subtract_list(row['a'], row['b']), axis=1)
df['bool'] = 5 <= df['sum'] <= 10
I'm getting the following error:
Traceback (most recent call last):
File "G:/My Drive/School/allele_segregation_analysis/test.py", line 15, in <module>
df['bool'] = pd.Series(5 <= df['sum'] <= 10)
File "C:\Users\Gal\PycharmProjects\venv\lib\site-packages\pandas\core\generic.py", line 1330, in __nonzero__
f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
If it's one condition as in:
df['bool'] = df['sum'] <= 10
it works perfectly. how do I set more than one logical condition?
Update: Using two separate conditions with an '&' rather than 'and' between them seems to work. Not sure what the difference is but problem solved I guess.
df['bool'] = (5 <= df['sum']) & (df['sum'] <= 10)