簡體   English   中英

Python 中的 Pandas Dataframe 系列中的一系列兩個列表的元素乘法

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

我有一個 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'])) )

目的是得到以下output:

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)

output 是:

  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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM