Home > Back-end >  I am trying to use pandas.DataFrame.replace to replace cells that contain lists with a single values
I am trying to use pandas.DataFrame.replace to replace cells that contain lists with a single values

Time:09-24

I have a column of a dataframe which contains 6 unique values of:

1, 2, 3, [1,2], [2,3], [1,2,3]

I am trying use pandas.DataFrame.replace to replace [1,2] with 4 when i have tried the code below:

x = df2['lockdown_level'].replace([1,2],4)

i get an output:

4, 4, 3, [1,2], [2,3], [1,2,3]

whereas i want the output of the unique values to be:

1, 2, 3, 4, [2,3], [1,2,3]

Does anyone have any suggestions to replace a list with a single value?

CodePudding user response:

I would it do like this: df2['lockdown_level'].apply(lambda x: 4 if x==[1, 2] else x)

Eleonora

  • Related