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

Fill empty list in array column of pandas dataframe

I need to fill the empty list in my dataframe array column using some string

|  array      |
|-------------|
|   []        |
|['pos','neg']|
|   []        |

I want to replace empty list with string value

|  array      |
|-------------|
|['neg']      |
|['pos','neg']|
|['neg']      |

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

>Solution :

One option using boolean indexing:

m = df['array'].str.len().eq(0)
df.loc[m, 'array'] = [['neg']]*m.sum()

Or with a loop:

df['array'] = [x if x else ['neg'] for x in df['array']]

# slower variant
# df['array'] = df['array'].apply(lambda x: x if x else ['neg'])

output:

        array
0       [neg]
1  [pos, neg]
2       [neg]

Used input:

df = pd.DataFrame({'array': [[], ['pos', 'neg'], []]})
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