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:
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?
CodePudding user response:
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