Pandas: replace string with special characters

Viewed 59

I have a dataframe (see after) in which I have two columns containing either a list of patients or an empty list (like that [''] ). I want to remove the empty list

What i have:

Homozygous_list heterozygous_list
[Patient1,Patient2] ['']
[''] [Patient1]

What i want:

Homozygous_list heterozygous_list
[Patient1,Patient2]
[Patient1]

I try several thing like :

variants["Homozygous_list"].replace("['']","", regex=True, inplace=True)

or

variants["Homozygous_list"].replace("\[''\]","", regex=True, inplace=True)

or

variants["Homozygous_list"] = variants["Homozygous_list"].replace("['']","", regex=True)

etc but nothing seems to work.

1 Answers

If you really have lists of strings, use applymap:

df = df.applymap(lambda x: '' if x==[''] else x)  # or pd.NA in place of ''

output:

       Homozygous_list  heterozygous_list
0  [Patient1, Patient2]                  
1                              [Patient1]

used input:

df = pd.DataFrame({'Homozygous_list ': [['Patient1','Patient2'], ['']],
                   'heterozygous_list': [[''], ['Patient1']]})
Related