-1

I would like to get the average of ColA when ColB is between 7 and 8. So in this case it would be 5.5. I have tried:

Avg = ColA[7 <= ColB <= 8].mean()

Sample of data

The problem is that I get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

If I use just one condition, then it executes without errors.

Avg =ColA[ColB >= 7].mean()
print(Avg)

How can I use get the average of one column when the values of a different column are between two set va

j__carlson
  • 1,346
  • 3
  • 12
  • 20
CRgene
  • 3
  • 3
  • 1
    [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – It_is_Chris Aug 18 '21 at 19:31
  • Are you actually using pandas? You should tag your post accordingly. – jarmod Aug 18 '21 at 19:33

1 Answers1

0

Use the pandas between function:

df.loc[df['ColB'].between(7, 8), 'ColA'].mean()
Aryerez
  • 3,417
  • 2
  • 9
  • 17
  • This worked perfectly. I found that you can also set the inclusion ex. .between(1, 4, inclusive="neither") the options are inclusive{“both”, “neither”, “left”, “right”} – CRgene Aug 19 '21 at 17:17