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

Counting the sum of a list in pandas dataframe column

I have a dataframe where column "lists" has lists:

l = ({'lists' : [[2,4,6],[8,10,12],[14,16,18]]})

df = pd.DataFrame(data = l)

I’ trying to add a new column that is the sum of the elements in these lists:

    lists           sum
0   [2, 4, 6]       12
1   [8, 10, 12]     30
2   [14, 16, 18]    48

So far I’ve tried:

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

df['sum'] = [sum(a) for a in zip(*df['lists'])]

but this sums the elements from all lists for example on row 0 the sum would be 2+8+14=24

How can I change the code to sum the elements inside one list?

>Solution :

Call sum in Series.apply:

df['sum'] = df['lists'].apply(sum)

Or list comprehension without zip:

df['sum'] = [sum(a) for a in df['lists']]

print (df)
          lists  sum
0     [2, 4, 6]   12
1   [8, 10, 12]   30
2  [14, 16, 18]   48
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