0

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)
Gal
  • 13
  • 3
  • Does this answer your question? [Pandas: Filtering multiple conditions](https://stackoverflow.com/questions/48978550/pandas-filtering-multiple-conditions) – Mateo Torres Nov 24 '20 at 05:15
  • Try `df["sum"].between(5, 10)`? – Chris Nov 24 '20 at 05:15
  • df[['sum', 'difference']] this line is also giving me error of "['sum1' 'difference'] not in index", also off-topic: avoid using reserved keywords as column names like sum and bool. – wheezay Nov 24 '20 at 05:34

1 Answers1

0

Below Code would help you:

df['bool'] = (5 <= df['sum']) and (df['sum'] <= 10)

while comparing the same value with 2 conditions you need to put and

Subbu VidyaSekar
  • 2,503
  • 3
  • 21
  • 39