Harper
Harper

Reputation: 65

Pandas - Count number of elements in each series

I have a table like this:

ID,Variation_price
1,{X:1, Y:2, Z:3}    
2,{}
3,{X:5, W:6}

How can I count the number of items for each ID to get this result:

1: 3
2: 0
3: 2

Upvotes: 3

Views: 1273

Answers (4)

Bharath_Raja
Bharath_Raja

Reputation: 642

You can use the following to get the length of a dictionary.

df['count_n'] = 0.0
for i in range(len(df)):
    df.loc[i, 'count_n']=len(df.loc[i,'Variation'])

Upvotes: 1

BENY
BENY

Reputation: 323396

Let us do

df['count_n']=df['Variation'].str.len()

If the data type is string

df['count_n']=df['Variation'].str.count(':')

Upvotes: 4

Allen Qin
Allen Qin

Reputation: 19957

If your Variation column is string type:

import ast
df.set_index('ID').Variation.apply(ast.literal_eval).apply(len)

If your Variation column is dict type:

df.set_index('ID').Variation.apply(len)

Upvotes: 0

Thanh Nguyen
Thanh Nguyen

Reputation: 912

you can do len() to get the number of the elements per list. Example:

for index_, row_ in iterrow(tables)
    print(len(row_))

Upvotes: 0

Related Questions