Alex
Alex

Reputation: 167

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

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.

Upvotes: 1

Views: 1224

Answers (1)

jezrael
jezrael

Reputation: 862611

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+')

Upvotes: 3

Related Questions