Home > Enterprise >  Replace a column with some [] in it with [0,0,1,1] in pandas
Replace a column with some [] in it with [0,0,1,1] in pandas

Time:07-28

I have dataframe with 26684 rows which looks like below.


    | patients | new_label      |
    | -------- | -------------- |
    | 0004cfab | []             |
    | 000924cf | []             |
    | 001916b8 | [316.0,318.0]  |
    | 0010f549 | []             |
    | 000db696 | [345.0,390.0]  |

I want the result like beow.


    | patients | new_label      |
    | -------- | -------------- |
    | 0004cfab | [0,0,1,1]      |
    | 000924cf | [0,0,1,1]      |
    | 001916b8 | [316.0,318.0]  |
    | 0010f549 | [0,0,1,1]      |
    | 000db696 | [345.0,390.0]  |

I want to replace every occurence of [] with [0,0,1,1] in the column new_label. I am new to pandas so I do not know how to go on to do this.I do was not able to find a a similar question onthe site.Thanks for the help.

CodePudding user response:

You can call apply() and then call a lambda function from it:

df["new_label"] = df["new_label"].apply(lambda x: [0, 0, 1, 1] if len(x) == 0 else x)

(A similar question)

CodePudding user response:

If your new_label column is string type, you can use

df['new_label'] = df['new_label'].mask(df['new_label'].astype(str).eq('[]'), '[0,0,1,1]')
  • Related