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

Viewed 93

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.

3 Answers

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]')

I think this might work, you can use replace:

df.new_label = df.new_label.replace([], [0,0,1,1])
print(df)

>>> 
 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]  

You can't replace lists in a vectorial way.

Use a list comprehension:

df['new_label'] = [x if x else [0, 0, 1, 1] for x in df['new_label']]

output:

   patients       new_label
0  0004cfab    [0, 0, 1, 1]
1  000924cf    [0, 0, 1, 1]
2  000db696  [316.0, 318.0]
3  000924cf    [0, 0, 1, 1]
4  000db696  [345.0, 390.0]
Related