Search code examples
pythonpandasattributeerror

AttributeError when using while loop for dataframes columns


I was trying to solve an issue regarding deleting the last column of a dataframe until a certain column-length criteria is met, so I tried working on a very basic example before applying it to real problem but I am meeting this error I'm not too sure solve:

import pandas as pd
import numpy as np
a = {'ear':[1,3,32,2],'aear':[53,4,3,22],'was':[23,3,2,4]}
df = pd.DataFrame(a)
print(df.columns)
print(len(df.columns))
while len(df.columns) > 1: 
    df = df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
print(df)

Output:

was
3
Traceback (most recent call last):
  File "C:\Users\Celius.Stingher\Desktop\PYTHON\soo.py", line 7, in <module>
    while len(df.columns) > 1:
AttributeError: 'NoneType' object has no attribute 'columns'

Could anyone please explain the source of the issue, because len(df.columns) is indeed resulting in 3, but using it in the while loop yields the error. Thanks a lot


Solution

  • this is because you use inplace=True. If you use inplace=True, drop returns None and you assign that to the df-variable again.

    So the following code should do, what you want:

    import pandas as pd
    import numpy as np
    a = {'ear':[1,3,32,2],'aear':[53,4,3,22],'was':[23,3,2,4]}
    df = pd.DataFrame(a)
    print(df.columns)
    print(len(df.columns))
    while len(df.columns) > 1: 
        df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
    print(df)