Home > database >  The correct way to get the size of a list
The correct way to get the size of a list

Time:11-19

I have a dataframe with one column and one row like:

list_id
12,13,14,16

The list_id column type is Object:

df['list'].dtypes => Object

When I try to get the number of elements in this column

l = list(df.list_id)

len(l) => 1

Or

len(df['list_id'] => 1

Why I am getting 1 instead of 4?

I want to get the count of elements as 4. What Can I do?

CodePudding user response:

Example

data = {'list_id': {0: '12,13,14,16'}} 
df = pd.DataFrame(data)

Code

df['list_id'].str.split(',').str.len()

Result

0    4
Name: list_id, dtype: int64



if you want get only 4 not series, use following code:

df['list_id'].str.split(',').str.len()[0]

CodePudding user response:

If you have actual lists in the list_id column:

df['list_id'].str.len()

Note that if you have strings this will give you an incorrect result.*

If you have strings, you can count the number of ',' and add 1 (except if the string is empty'):

df['list_id'].str.count(',')   df['list_id'].ne('')

Output:

0    4
Name: list_id, dtype: int64
  • Related