get the length of dictionary within a dataframe

Viewed 277

I am currently learning pandas and would like to know how can i get filter the rows whose column (that is a dictionary) has more than 3 keys in it. For example,

data = {'id':[1,2,3], 'types': [{1: 'a', 2:'b', 3:'c'},{1: 'a', 2:'b', 3:'c', 4:'d'}, {1: 'a', 2:'b', 3:'c'}]}
df = pd.dataframe(data)

How can i get the rows where the len of dictionary in column types is > 3 I tried doing

df[len(df['types']) > 3]

but it doesnt work. Any simple solution out there?

1 Answers

Use Series.apply or Series.map:

df = df[df['types'].apply(len) > 3]
#alternative
#df = df[df['types'].map(len) > 3]
print (df)
   id                             types
1   2  {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

Or Series.str.len:

df = df[df['types'].str.len() > 3]
Related