Home > Enterprise >  How to count length of column while some rows have NaN in it?
How to count length of column while some rows have NaN in it?

Time:11-27

I have a pandas dataframe. In column I have list. But, some rows NaN. I want to find length of each list, in case it is NaN, I want 0 as length.

My_column
[1, 2]-> should return 2
[] -> should return 0
NaN -> should return 0

Any help?

Thank you.

CodePudding user response:

df['column'].str.len().fillna(0).astype(int)

CodePudding user response:

You can check to see if the item is a list:

  • If it is a list - identify the length of that list
  • If it is not a list (eg. np.nan) - then set to zero.
output = [len(x) if isinstance(x, list) else 0 for x in df['column']]


Here is an example using your inputs

import pandas as pd
import numpy as np

df = pd.DataFrame({'column': [['a','b'], np.nan, []]})

output = [len(x) if isinstance(x, list) else 0 for x in df['column']]

print(output)

OUTPUT:

[2, 0, 0]
  • Related