Home > Software engineering >  Fill empty list in array column of pandas dataframe
Fill empty list in array column of pandas dataframe

Time:10-27

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

CodePudding user response:

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'], []]})
  • Related