Search code examples
pythonpandaslistdataframemultiplication

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


I have a dataframe where there are two series, and each contains a number of lists. I would like to perform element-wise multiplication of each list in 'List A' with the corresponding list in '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'])) )

The aim is to get the following output:

print(df['New'])

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

However I am getting the following error:

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

Solution

  • Your code is almost there. Mostly, you need to pass axis=1 to apply:

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

    The output is:

      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]