为了账号安全,请及时绑定邮箱和手机立即绑定

将列表的两个 pandas 列彼此分开

将列表的两个 pandas 列彼此分开

墨色风雨 2023-06-20 16:08:42
我有一个这样的 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]尝试了很多不同的方法 - 但总是出错。尝试:#attempt1df['col1'].div(df['col2'], axis=0)#attempt2from operator import truedivfor i in df.col1:     a = np.array(df['col1'])     for t in df.col2:         b = np.array(df['col2'])         x = a/b         print(x)#attempt3for i in df.index:    a = col1    b = col2    x = map(truediv, a, b)#attempt4a = col1b = col2result = [x/y for x, y in zip(a, b)]#then apply to df#attempt5a = col1b = col2result = a/bprint(percent_matched)#then #apply to df>>>TypeError: unsupported operand type(s) for /: 'list' and 'list'有任何想法吗?
查看完整描述

4 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

  • 用于.applymap将列转换为np.arrays

  • 然后用来.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)


查看完整回答
反对 回复 2023-06-20
?
红颜莎娜

TA贡献1842条经验 获得超12个赞

您可以将列表理解与应用一起使用,这是以两个列表的长度相同为条件的


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)


查看完整回答
反对 回复 2023-06-20
?
开满天机

TA贡献1786条经验 获得超12个赞

df=df.apply(pd.Series.explode)#

df['result']=(df.col1.div(df.col2))

df.groupby(level=0)['result'].agg(list).reset_index()


查看完整回答
反对 回复 2023-06-20
?
慕勒3428872

TA贡献1848条经验 获得超6个赞

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


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

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


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


查看完整回答
反对 回复 2023-06-20
  • 4 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信