Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

count number of elements in a list inside a dataframe

Assume that we have a dataframe and inside the dataframe in a column we have lists. How can I count the number per list? For example

A                              B
(1,2,3)                       (1,2,3,4)
(1)                           (1,2,3)

I would like to create 2 new columns with the count of each column. something like the following

A                              B              C              D         
(1,2,3)                       (1,2,3,4)       3              4
(1)                           (1,2,3)         1              3

where C corresponds to the number of the elements in the column A for that row, and D for the number of elements in the list in column B for that row

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I cannot just do

df['A'] = len(df['A'])

Because that returns the len of my dataframe

>Solution :

You can use the .apply method on the Series for the column df['A'].

>>> import pandas
>>> import pandas as pd
>>> pd.DataFrame({"column": [[1, 2], [1], [1, 2, 3]]})
      column
0     [1, 2]
1        [1]
2  [1, 2, 3]
>>> df = pd.DataFrame({"column": [[1, 2], [1], [1, 2, 3]]})
>>> df["column"].apply
<bound method Series.apply of 0       [1, 2]
1          [1]
2    [1, 2, 3]
Name: column, dtype: object>
>>> df["column"].apply(len)
0    2
1    1
2    3
Name: column, dtype: int64
>>> df["column"] = df["column"].apply(len)
>>> 

See Python Pandas, apply function for a more general discussion of apply.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading