如何将python集转换为numpy数组? [英] How to convert a python set to a numpy array?

查看:111
本文介绍了如何将python集转换为numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python中使用set操作在两个numpy数组之间执行对称差异.但是,结果是一个集合,我需要将其转换回numpy数组以继续前进.有没有办法做到这一点?这是我尝试过的:

I am using a set operation in python to perform a symmetric difference between two numpy arrays. The result, however, is a set and I need to convert it back to a numpy array to move forward. Is there a way to do this? Here's what I tried:

a = numpy.array([1,2,3,4,5,6])
b = numpy.array([2,3,5])
c = set(a) ^ set(b)

结果是一组:

In [27]: c
Out[27]: set([1, 4, 6])

如果我转换为numpy数组,它将整个集合放在第一个数组元素中.

If I convert to a numpy array, it places the entire set in the first array element.

In [28]: numpy.array(c)
Out[28]: array(set([1, 4, 6]), dtype=object)

但是,我需要的是这样:

What I need, however, would be this:

array([1,4,6],dtype=int)

我可以遍历元素以一次一转换,但是我将有100,000个元素,并希望有一个内置函数来保存循环.谢谢!

I could loop over the elements to convert one by one, but I will have 100,000 elements and hoped for a built-in function to save the loop. Thanks!

推荐答案

不要将numpy数组转换为执行异或的数组.

Don't convert the numpy array to a set to perform exclusive-or. Use setxor1d directly.

>>> import numpy
>>> a = numpy.array([1,2,3,4,5,6])
>>> b = numpy.array([2,3,5])
>>> numpy.setxor1d(a, b)
array([1, 4, 6])

这篇关于如何将python集转换为numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆