1

I have some kind of this table

No   app_list
1    ['com.lenovo.anyshare.gps', 'com.UCMobile.intl'] 
2    []
3    ['com.rarlab.rar', 'com.kreditpintar', 'com.whatsapp']

and I want to count that app_list, and be like this

No  app_list                                                      count
1   ['com.lenovo.anyshare.gps', 'com.UCMobile.intl']              2
2   []                                                            0
3   ['com.rarlab.rar', 'com.kreditpintar', 'com.whatsapp']        3

is there any way to get it done like that ? thank you

Napier
  • 227
  • 2
  • 10

1 Answers1

2

Get the length of each list in the row and add it to a new column:

###### Recreating OP's dataframe ##########
import pandas as pd
No = [1, 2, 3]
app_list = [['com.lenovo.anyshare.gps', 'com.UCMobile.intl'], [], ['com.rarlab.rar', 'com.kreditpintar', 'com.whatsapp']]
df = pd.DataFrame({"No":No, "app_list":app_list})
###########################################

# Best practice: vectorial way, given by @mozway
df['Count'] = df['app_list'].str.len()


# Alternative: list comprehension way, by me:
df["Count"] = [len(x) for x in df.app_list]

Output:

    No  app_list                                         Count
0   1   [com.lenovo.anyshare.gps, com.UCMobile.intl]      2
1   2   []                                                0
2   3   [com.rarlab.rar, com.kreditpintar, com.whatsapp]  3
Michael S.
  • 3,050
  • 4
  • 19
  • 34
  • 1
    If you have lists: `df['Count'] = df['app_list'].str.len()` is the vectorial way to do it ;) – mozway Jul 21 '22 at 14:47
  • 1
    I have a blind spot for this and always default to list comprehension. Yours obviously makes more sense and reads better. I will update my answer to include both but prioritize yours. – Michael S. Jul 21 '22 at 14:49