Home > Back-end >  How to count the number of values for each index in Python->Pandas->DataFrame
How to count the number of values for each index in Python->Pandas->DataFrame

Time:12-29

I have the next DataFrame:

a = [{'x1':'a, b, c, d, e, f'}, {'x1':'a, b, c'}, {'x1':'a'}]
df = pd.DataFrame(a)
print(df)

I need to create the new column -> len_x1 in DataFrame and insert into it the amount of values in each cell.

I need the next result:

enter image description here

I will be grateful for help.

CodePudding user response:

If possible count separator and add 1 use:

df['x1_len'] = df['x1'].str.count(',')   1
print (df)
                 x1  x1_len
0  a, b, c, d, e, f       6
1           a, b, c       3
2                 a       1

Or count words:

df['x1_len'] = df['x1'].str.count('\w ')
  • Related