Divide two pandas columns of lists by each other

  • Use .applymap to convert the columns to np.arrays
  • Then use .div to divide the columns
  • If result must be rounded, tack on .apply(lambda x: np.round(x, 3)), when calculating that column.
    • np.round()
    • df['result'] = df.col1.div(df.col2).apply(lambda x: np.round(x, 3))
import numpy as np
import pandas as pd

data = {'col1': [[1,3,4,5], [1,4,5,5], [1,3,4,8]], 'col2': [[3,3,6,2], [3,8,4,3], [8,3,7,2]]}

df = pd.DataFrame(data)

# convert columns to arrays
df = df.applymap(np.array)

# divide the columns
df['result'] = df.col1.div(df.col2)

You can use list comprehension with apply, this is conditional on both the lists being of same length

df['result'] = df.apply(lambda x: [np.round(x['col1'][i]/x['col2'][i], 2) for i in range(len(x['col1']))], axis = 1)

    col1            col2            result
0   [1, 3, 4, 5]    [3, 3, 6, 2]    [0.33, 1.0, 0.67, 2.5]
1   [1, 4, 5, 5]    [3, 8, 4, 3]    [0.33, 0.5, 1.25, 1.67]
2   [1, 3, 4, 8]    [8, 3, 7, 2]    [0.12, 1.0, 0.57, 4.0]

Edit: As @TrentonMcKinney suggested, this can be done without using LC. This solution capitalized on Numpy's vectorized operations,

df.apply(lambda x: np.round(np.array(x[0]) / np.array(x[1]), 3), axis=1)

df=df.apply(pd.Series.explode)#
df['result']=(df.col1.div(df.col2))
df.groupby(level=0)['result'].agg(list).reset_index()

Tags:

Python

Pandas