来自 Python 中单独的 Pandas Dataframe 系列的一系列两个列表的逐元素乘法

Element-wise multiplication of a series of two lists from separate Pandas Dataframe Series in Python

我有一个数据框,其中有两个系列,每个系列都包含多个列表。我想对 'List A' 中的每个列表与 'List 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')

您的代码就快完成了。大多数情况下,您需要通过 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]

您可以使用numpy

n [50]: df
Out[50]:
  ref     List A     List B
0   A  [0, 1, 2]  [0, 1, 2]
1   B  [2, 3, 4]  [2, 3, 4]
2   C  [3, 4, 5]  [3, 4, 5]
3   D  [4, 5, 6]  [4, 5, 6]

In [51]: df["New"] = np.multiply(np.array(df["List A"].tolist()), np.array(df["List B"].tolist())).tolist()

In [52]: df
Out[52]:
  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]

你也可以使用operator模块

In [63]: df
Out[63]:
  ref     List A     List B
0   A  [0, 1, 2]  [0, 1, 2]
1   B  [2, 3, 4]  [2, 3, 4]
2   C  [3, 4, 5]  [3, 4, 5]
3   D  [4, 5, 6]  [4, 5, 6]

In [64]: import operator

In [65]: df["New"] = df.apply(lambda x:list(map(operator.mul, x["List A"], x["List B"])), axis=1)

In [66]: df
Out[66]:
  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]