简体   繁体   中英

Create new column of count number of elem in row of dict of pandas dataframe

I have the following df:

values_list = [[15, {'num':[0]}, 100], [20, {'num':[0]}, 50], [25, {'num':[0]}, 80],
               [45, {'num':[0], 'option':[1]}, 48], [40, {'num':[0]}, 70], [41, {'num':[0]}, 90],
               [51, {'num':[0]}, 111]]
  

df = pd.DataFrame(values_list, columns=['Field_1', 'Field_2', 'Field_3'])

Fields_2 is a collomn of dict. I would like to perform the len following function and put it in a new column if I do:

len(df.Field_2[3])

output = 2 (and 1 for the other indexes)

What I would like as result is a DF as follows

预期结果

I tried the following lambda function but it doesn't seem to work as I get a column with the len of the column not the row

df = df.assign(elem=lambda x: (len(x['Field_2'])))

i would have expected something more like this but this gives an error

df = df.assign(elem=lambda x: (x[len(x['Field_2'])]))

Could someone point me out how to solve this issue?

Use len per values in Series.apply or Series.map :

df = df.assign(elem=lambda x: x['Field_2'].apply(len))

print (df)
   Field_1                      Field_2  Field_3  elem
0       15                 {'num': [0]}      100     1
1       20                 {'num': [0]}       50     1
2       25                 {'num': [0]}       80     1
3       45  {'num': [0], 'option': [1]}       48     2
4       40                 {'num': [0]}       70     1
5       41                 {'num': [0]}       90     1
6       51                 {'num': [0]}      111     1

Or solution from @Don'tAccept, thank you:

df = df.assign(elem=df['Field_2'].apply(len))

Or solution from @Asish M., thank you:

df = df.assign(elem=df['Field_2'].str.len())

The below should work:

df["elem"] = df["Field_2"].apply(len)

You can use lambda when you convert each dictionary to list and take its length:

df['elem'] = df['Field_2'].apply(lambda x: len(list(x)))

Output:

       Field_1                       Field_2    Field_3   elem
0           15                  {'num': [0]}        100      1
1           20                  {'num': [0]}         50      1
2           25                  {'num': [0]}         80      1
3           45   {'num': [0], 'option': [1]}         48      2
4           40                  {'num': [0]}         70      1
5           41                  {'num': [0]}         90      1
6           51                  {'num': [0]}        111      1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM