【问题标题】:Element-wise multiplication of a series of two lists from separate Pandas Dataframe Series in PythonPython中不同Pandas Dataframe系列的一系列两个列表的元素乘法
【发布时间】:2020-07-26 10:13:42
【问题描述】:

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

【问题讨论】:

    标签: python pandas list dataframe multiplication


    【解决方案1】:

    您的代码几乎就在那里。大多数情况下,您需要通过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]
    

    【讨论】:

      【解决方案2】:

      您可以使用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]
      

      【讨论】:

        猜你喜欢
        • 2013-03-04
        • 2021-11-22
        • 1970-01-01
        • 2013-09-06
        • 2014-07-24
        • 2015-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多