将列表的两个熊猫列彼此分开

时间:2020-08-25 22:13:37

标签: python pandas

我有这样的df:

col1        col2
[1,3,4,5]   [3,3,6,2]
[1,4,5,5]   [3,8,4,3]
[1,3,4,8]   [8,3,7,2]

尝试将col1和col2中的列表中的元素划分在一起以获取结果列中的内容:

col1        col2        result
[1,3,4,5]   [3,3,6,2]   [.33,1,.66,2.5]
[1,4,5,5]   [3,8,4,3]   [.33,.5,1.25,1.66]
[1,3,4,8]   [8,3,7,2]   [.33,1,.57,4]

尝试了许多不同的方法-但总是会出错。

尝试

#attempt1
df['col1'].div(df['col2'], axis=0)

#attempt2
from operator import truediv

for i in df.col1:
     a = np.array(df['col1'])
     for t in df.col2:
         b = np.array(df['col2'])
         x = a/b
         print(x)


#attempt3
for i in df.index:
    a = col1
    b = col2
    x = map(truediv, a, b)

#attempt4
a = col1
b = col2
result = [x/y for x, y in zip(a, b)]
#then apply to df

#attempt5
a = col1
b = col2
result = a/b
print(percent_matched)
#then #apply to df

>>>TypeError: unsupported operand type(s) for /: 'list' and 'list'

有什么想法吗?

4 个答案:

答案 0 :(得分:6)

  • 使用.applymap将列转换为np.array s
  • 然后使用.div划分列
  • 如果必须对result进行四舍五入,请在计算该列时附加.apply(lambda x: np.round(x, 3))
    • 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)

答案 1 :(得分:4)

您可以将列表理解与apply一起使用,这取决于两个列表的长度相同

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]

编辑:正如@TrentonMcKinney所建议的那样,无需使用LC即可完成此操作。该解决方案利用了Numpy的矢量化操作,

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

答案 2 :(得分:3)

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

答案 3 :(得分:1)

如果它们很大,最好将它们转换为np.arrays然后进行除法:

df["col1"] = df["col1"].apply(np.array)
df["col2"] = df["col2"].apply(np.array)

df["output"] = df.col1/df.col2