1

When I try to rename and drop columns from pandas data.frame I'm experiencing an error saying >AttributeError: 'NoneType' object has no attribute 'drop'.

Pandas df.rename.drop.groupby.reset_index order is always confuses me. What is the correct syntax I should be following when want to reshape the pandas df ?

raw_data = {'patient': [1, 1, 1, 2, 2],
        'obs': [1, 2, 3, 1, 2],
        'treatment': [0, 1, 0, 1, 0],
        'score': ['strong', 'weak', 'normal', 'weak', 'strong'],    
        'tr': [1,2,3,4,5],
        'tk': [6,7,8,9,10],
        'ak': [11,12,13,14,15]

        }



df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score','tr','tk','ak'])

df

   patient  observation  treatment Dr_score  tr  tk  ak
0        1            1          0   strong   1   6  11
1        1            2          1     weak   2   7  12
2        1            3          0   normal   3   8  13
3        2            1          1     weak   4   9  14
4        2            2          0   strong   5  10  15



def rename_drop(df):

    df=df.rename(columns = {'obs':'observation', 'score':'Dr_score'},inplace = True).drop('tk',axis=1,inplace=True)

    return df


rename_drop(df)

AttributeError: 'NoneType' object has no attribute 'drop'

Alexander
  • 4,527
  • 5
  • 51
  • 98
  • 2
    remove both `inplace=True`, it's redundant since you already assign it back to `df`. This will work: `df = df.rename(columns = {'obs':'observation', 'score':'Dr_score'}).drop(columns='tk')` – Erfan Jan 19 '20 at 22:18
  • `df=df.rename(columns = {'obs':'observation', 'score':'Dr_score'}).drop('tk',axis=1)` – ansev Jan 19 '20 at 22:19
  • 1
    I though I should be doing `inplace=True` because I want to change the original df – Alexander Jan 19 '20 at 22:21

1 Answers1

2

Your error lies in the use of inplace=True (both in the rename and drop operations). This will return a NoneType object instead of the expected dataframe to which to apply drop.

Try:

df.rename(columns = {'obs':'observation', 'score':'Dr_score'}, inplace = False).drop('tk',axis=1,inplace=False)

EDIT: incorporated line above in original function:

def rename_drop(df):

   df = df.rename(columns = {'obs':'observation', 'score':'Dr_score'}, inplace = False).drop('tk',axis=1,inplace=False)

   return df
RubenB
  • 525
  • 3
  • 10
  • I think you misread my answer. I set inplace=False, so it does return a dataframe. In fact, inplace is False by default, hence making my line of code the same as you wrote in your comment to OP. – RubenB Jan 19 '20 at 22:23
  • Okey but still incorrect... where are you saving the dataframe?.. you need `df =df....` ....... `inplace` is False by default. I think `df=df.rename(columns = {'obs':'observation', 'score':'Dr_score'}).drop('tk',axis=1)` is the correct solution ( and dup) – ansev Jan 19 '20 at 22:26