0

I have to read excel and if column value meet some condition i have to add some thing. Below are the input excel enter image description here

I just need to take Name and Values if Value > 50

Below is my script.

   df = pd.read_excel(file)
   print (df[df['Value'] > 50]) #prints the name and values 
   if df[df['Value'] > 50]:
       print (df['Value'])

I am getting ValueError. ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Please help me.

Expected Output: enter image description here

  • Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – Guy Nov 12 '19 at 06:22
  • Hi Guy, Actually i have seen the ans, but i can't find proper solution. – Mohan Rao D Nov 12 '19 at 06:23
  • Do you need `df.loc[df['Value'] > 50, 'Name']` ? Because not sure if understand `if df[df['Value'] > 50]`, because like you test before `df[df['Value'] > 50]` return DataFrame. Or you need `if (df['Value'] > 50).any():` test if at least one >50 value in column `Value` ? – jezrael Nov 12 '19 at 06:24
  • @jezrael, I tried with .any, .empty and .bool, but these methods comparing the whole Value column, but I need to take each and every Boolean expressions. – Mohan Rao D Nov 12 '19 at 06:27
  • @MohanRaoD - What is expected output? – jezrael Nov 12 '19 at 06:27
  • So you need `df1 = (df[df['Value'] > 50])` `print (df1)`? – jezrael Nov 12 '19 at 06:31
  • @jezrael, yeah, Also, if condition must be there. I have to add some more functions and methods in if condition. – Mohan Rao D Nov 12 '19 at 06:33
  • @MohanRaoD - Can you be more specific? – jezrael Nov 12 '19 at 06:35

2 Answers2

1

If want test at least one value >50 before filtering by mask use any for scalar True or False:

df = pd.read_excel(file)

mask = df['Value'] > 50
if mask.any():
    df1 = df[mask]
    print (df1)

If if statement is not necessary:

df1 = df[df['Value'] > 50]
print (df1)

You can also check using if truth statements with pandas.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Dear Andreson, thanks for your reply. But my requirement is without using the DOT (.any,.bool, .empty, .all ..etc) operator should run the if condition with each and every Boolean expression (True or False), Kindly advise do have any idea? – Mohan Rao D Nov 15 '19 at 16:23
0

Assuming you want to print all the values greater than 50, do:

print(df[df['Value'] > 50].values)
Aryerez
  • 3,417
  • 2
  • 9
  • 17