Home > OS >  How do I replace the list of nan with list of zeroes in a pandas dataframe cell
How do I replace the list of nan with list of zeroes in a pandas dataframe cell

Time:02-11

I have this dataframe. How do I replace the list of nan with list of zeroes?

a   b            
1   [nan, nan]
5   [nan, nan, nan]
0   [0, 0]

CodePudding user response:

One option is explode fillna groupby:

df['b'] = df['b'].explode().fillna(0).groupby(level=0).agg(list)

Another option is list comprehension:

df['b'] = [[0 if isinstance(x, float) and np.isnan(x) else x for x in lst] for lst in df['b']]

Output:

   a          b
0  1     [0, 0]
1  5  [0, 0, 0]
2  0     [0, 0]

CodePudding user response:

How about a list comprehension?

df['b'] = [[y or 0 for y in x] for x in df['b']]
df
 
   a          b
0  1     [0, 0]
1  5  [0, 0, 0]
2  0     [0, 0]
  • Related