python - 将两列 Pandas 列表彼此分开

标签 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'
有任何想法吗?

最佳答案

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

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)

关于python - 将两列 Pandas 列表彼此分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63587821/

相关文章:

python-3.x - 使用回归线在 Altair 中可视化多列的快速方法

python - 查找具有公差的重复项并分配给 Pandas 中的一个集合

python - 如何导入虚拟环境中未安装的python-mysql包?

python - 使用 imap 获取电子邮件附件,但无论电子邮件是从 Outlook 客户端还是通过 Web 发送,都会得到不同的结果

python - 使用 python 从文章中提取数据的多个正则表达式模式

python - Pandas Python 正则表达式 : error: nothing to repeat

python - 根据 lengt 函数从 df 内的数组中检索值

python模块用密码保护现有的pdf文件

python - Pytest 无法通过标记 skipif 跳过类中的测试用例

python-3.x - 值错误: could not convert string to float: left_column_pixel