Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace elements of a pandas series with a list containing a single string

I am trying to replace the empty list in a pandas serie with a list containing a single string. Here is what I have:

a = pd.Series([ 
    [],
    [],
    ['a'],
    ['a'],
    ["a","b"]
])

The desired output is as following :

b = pd.Series([ 
    ['INCOMPLETE'],
    ['INCOMPLETE'],
    ['1'],
    ['1'],
    ["1","2"]
])

Where I try to replace the empty lists using boolean indexing, I get an automatic coercion of my list of a unique string to just string string:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a[a.map(len) == 0 ] = ['INCOMPLETE']
0    INCOMPLETE
1    INCOMPLETE
2           [a]
3           [a]
4        [a, b]

In contrast the manual replacement works a[0] = ['INCOMPLETE']

Does anyone have a workaround ? Thanks.

>Solution :

Use lambda function with if-else for replace empty string, because if comapre are processing like False:

a = a.apply(lambda x: x if x else ['INCOMPLETE'])
print (a)
0    [INCOMPLETE]
1    [INCOMPLETE]
2             [a]
3             [a]
4          [a, b]
dtype: object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading