Python Dataframe 添加两列包含列表

Python Dataframe add two columns containing lists

我有一个包含两列的数据框,每列包含列表作为元素。我想执行两个列表的行向元素加法。我的以下解决方案的灵感来自这个答案 Element-wise addition of 2 lists?

我的代码:

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

预期答案:

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

由于需要应用函数row-wise,所以只需要axis=1:

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

df['C'] = df[['A','B']].apply(lambda x: [i+j for i,j in zip(*x)], axis=1)

另一种选择是 explode 列表; sum;然后 groupby.agg 返回列表:

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

输出:

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