1

I have the following df and I am trying to see what the value is of the first row in the first column and if it is equal to a predetermined character in this case "0". I also tried:

if df[col_titles[0]].values[0] == x:
            print(True)
            df  = df.drop(x)

Which didn't work and had the exact same error (posted below).

  First Column Name Second Column Name Third Column Name Fourth Column Name
0                 0                  3                 6                  4
1                 2                  5                 5                  7

df = pd.DataFrame({'First Column Name':  ["0", 2],
        'Second Column Name': ["3", 5],
        'Third Column Name': ["6", 5],
        'Fourth Column Name': ["4", 7],
        })
col_titles = df.columns.values.tolist()
x = df[col_titles[0]].values[0]
print(x)

if df[col_titles[0]].values[0] == "0":
        print(True)
        df  = df.drop(df[col_titles[0]].values[0])

Returns

0
True
Traceback (most recent call last):
  File "test.py", line 42, in <module>
    df  = df.drop(x)
  File "C:\Python38\lib\site-packages\pandas\core\frame.py", line 3990, in drop
    return super().drop(
  File "C:\Python38\lib\site-packages\pandas\core\generic.py", line 3936, in drop
    obj = obj._drop_axis(labels, axis, level=level, errors=errors)
  File "C:\Python38\lib\site-packages\pandas\core\generic.py", line 3970, in _drop_axis
    new_axis = axis.drop(labels, errors=errors)
  File "C:\Python38\lib\site-packages\pandas\core\indexes\base.py", line 5017, in drop
    raise KeyError(f"{labels[mask]} not found in axis")
KeyError: "['0'] not found in axis"

Desired output

  First Column Name Second Column Name Third Column Name Fourth Column Name
1                 2                  5                 5                  7
JPWilson
  • 691
  • 4
  • 14
  • Does this answer your question? [How to apply a condition to pandas iloc](https://stackoverflow.com/questions/50292460/how-to-apply-a-condition-to-pandas-iloc) – David Erickson Sep 02 '20 at 00:15

2 Answers2

1

We do not for loop here

dfsub = df[df.iloc[:,0]!='0']
Out[13]: 
  First Column Name Second Column Name Third Column Name Fourth Column Name
1                 2                  5                 5                  7
BENY
  • 317,841
  • 20
  • 164
  • 234
1

This should give you the result you need:

df.loc[df['First Column Name'] != '0']

enter image description here

Mathew Paul
  • 181
  • 1
  • 4