Home > Software engineering >  how to replace same values in multiple columns in pandas dataframe
how to replace same values in multiple columns in pandas dataframe

Time:10-12

my dataframe looks like this:

    PD_DK    WARNSPEAK_DK
1    88         88
2    Nan         1    
3    88          1
4    1           1

here is my code:

df2.replace({['PD_DK','WARNSPEAK_DK','TIME1','TIME2','TIME3','TIME4','WARNBEHAV_DK','TIME5','TIME6','TIME7',
            'TIME8','WARNEMOTION_DK','TIME9','TIME10','TIME11','TIME12']: 88}, 999999, inplace=True)
# to check
df2['PD_DK'].value_counts()

and I got the output such as:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [31], in <cell line: 1>()
----> 1 df2.replace({['PD_DK','WARNSPEAK_DK','TIME1','TIME2','TIME3','TIME4','WARNBEHAV_DK','TIME5','TIME6','TIME7',
      2             'TIME8','WARNEMOTION_DK','TIME9','TIME10','TIME11','TIME12']: 88}, 999999, inplace=True)
      3 df2['PD_DK'].value_counts()

TypeError: unhashable type: 'list'

CodePudding user response:

IIUC use if need specify columns by list:

cols = ['PD_DK','WARNSPEAK_DK','TIME1','TIME2','TIME3','TIME4','WARNBEHAV_DK','TIME5','TIME6',
        'TIME7','TIME8','WARNEMOTION_DK','TIME9','TIME10','TIME11','TIME12']
df2[cols] = df2[cols].replace({88: 999999})

Or create nested dictionaries in dict comprehension:

df2 = df2.replace({x:{88: 999999} for x in cols})
  • Related