Home > Enterprise >  Rename None in a list under pandas column
Rename None in a list under pandas column

Time:12-20

Let's say I have the following dataframe:

Value
[None, A, B, C]
[None]

I would like to replace None value in the column with none but it seems I couldn't figure out it.

I used this but not working.

df['Value'] = df['Value'].str.replace('None','none')

CodePudding user response:

None is a built-in type in Python, so if you want to make it lowercase, you have to convert it to a string.

There is no built-in way in Pandas to replace values in lists, but you can use explode to expand all the lists so that each individual item of each list gets its own row in the column, then replace, then group back together into the original list format:

df['Value'] = df['Value'].explode().replace({None: 'none'}).groupby(level=0).apply(list)

Output:

>>> df
             Value
0  [none, A, B, C]
1           [none]

CodePudding user response:

Here is a way using map()

df['Value'] = df['Value'].map(lambda x: ['none' if i == None else i for i in x])

Output:

             Value
0  [none, A, B, C]
1           [none]
  • Related