0

I have a few lines of code and I don't understand why I encounter this error and it doesn't return print 'help' 3 times.

import pandas as pd
d = {'lei': ['lei1', 'lei2'], 'B': [30, 40], 'C': [50, 60],'D': [70, 80],'E': [0, 90],'F': [0, 20]}
df = pd.DataFrame(data=d)
l = 'lei1'
l_index = df[df['lei'] == l].index
mm = ['B', 'C', 'D', 'E', 'F']
for m in mm:
    if df.loc[l_index][m]>0:
        print('help')

Thanks for your help!

Dario Bani
  • 123
  • 6
  • 1
    Please read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and try to trace through the code. What do you expect to be the result of `df.loc[l_index][m]`? In particular, what type do you expect it to have? Did you test that? What will you get if you compare that to an integer? What do you expect it to mean if you try to use *that* result with `if`? – Karl Knechtel May 22 '22 at 18:33
  • 2
    It's because `l_index` is an index containing one element, not a scalar. Which makes df.loc[l_index] a DataFrame, not a Series. – Zorgoth May 22 '22 at 18:35
  • @KarlKnechtel I would have expected the code to print 3 times 'help' since df.loc[l_index][m] should have picked the value 30 50 70 – Dario Bani May 22 '22 at 18:50
  • 1
    Just because it picks one value each time, doesn't make that value an integer. It's as @Zorgoth said: `df.loc` operations will give you another DataFrame, no matter the size of the match. Comparing a DataFrame to an integer also gives you a DataFrame. DataFrames (like Numpy arrays) cannot be converted to boolean, as explained in the linked duplicate. – Karl Knechtel May 22 '22 at 18:52
  • 1
    (actually, df.loc will give a Series if its argument is an integer) – Zorgoth May 22 '22 at 18:54
  • I see thanks! How can I then just extract just the value/string contained into the coordinates [row][column] that I have? – Dario Bani May 22 '22 at 18:55
  • 1
    Simply use the integer inside l_index instead of l_index itself. – Zorgoth May 22 '22 at 19:09

0 Answers0