首页 > 解决方案 > Python中来自不同Pandas Dataframe系列的一系列两个列表的元素乘法

问题描述

我有一个数据框,其中有两个系列,每个系列都包含许多列表。我想对“列表 A”中的每个列表与“列表 B”中的相应列表执行逐元素乘法。

df = pd.DataFrame({'ref': ['A', 'B', 'C', 'D'],
                   'List A': [ [0,1,2], [2,3,4], [3,4,5], [4,5,6] ],
                   'List B': [ [0,1,2], [2,3,4], [3,4,5], [4,5,6] ] })

df['New'] = df.apply(lambda x: (a*b for a,b in zip(x['List A'], x['List B'])) )

目的是获得以下输出:

print(df['New'])

0    [0, 1, 4]
1    [4, 9, 16]
2    [9, 16, 25]
3    [16, 25, 36]
Name: New, dtype: object

但是我收到以下错误:

KeyError: ('List A', 'occurred at index ref')

标签: pythonpandaslistdataframemultiplication

解决方案


您的代码几乎就在那里。大多数情况下,您需要通过axis=1才能申请:

df["new"] = df.apply(lambda x: list(a*b for a,b in zip(x['List A'], x['List B'])), axis=1)
print(df)

输出是:

  ref     List A     List B           new
0   A  [0, 1, 2]  [0, 1, 2]     [0, 1, 4]
1   B  [2, 3, 4]  [2, 3, 4]    [4, 9, 16]
2   C  [3, 4, 5]  [3, 4, 5]   [9, 16, 25]
3   D  [4, 5, 6]  [4, 5, 6]  [16, 25, 36]

推荐阅读