Home > database >  Python Dataframe add two columns containing lists
Python Dataframe add two columns containing lists

Time:04-30

I have a dataframe of two columns, each containing list as elements. I want to perform rowwise element additon of two lists. My below solution is inspired from this answer Element-wise addition of 2 lists?

My code:

df = pd.DataFrame({'A':[[1,2,3],[10,20]],'B':[[4,5,6],[40,50]]})

           A          B
0  [1, 2, 3]  [4, 5, 6]
1   [10, 20]   [40, 50]

df['C'] = df[['A','B']].apply(lambda x: list(map(add,x[0],x[1])))
df['C'] = 
    A   B
0  11  44
1  22  55

Expected answer:

df['C'] = 
   C
0 [5,7,9]
1 [50,70]

CodePudding user response:

Since you need to apply the function row-wise, you just need axis=1:

from operator import add
df['C'] = df[['A','B']].apply(lambda x: list(map(add,x[0],x[1])), axis=1)

An alternative option is to explode the lists; sum; then groupby.agg to get the lists back in:

df['C'] = df.explode(['A','B']).sum(axis=1).astype(int).groupby(level=0).agg(list)

Output:

           A          B          C
0  [1, 2, 3]  [4, 5, 6]  [5, 7, 9]
1   [10, 20]   [40, 50]   [50, 70]
  • Related