Python - Numpy数组中的字符串和整数

时间:2017-06-29 17:27:32

标签: python arrays python-2.7 numpy

我想创建一个包含3列的数组。第一个是字符串,另外两个是用于计算的整数。然后将通过append函数添加更多行(如下所示)。

问题是所有列似乎都被编码为字符串而不仅仅是第一个。如何获得数字的正确数据类型?

a = np.array([["String",1,2]])
a = np.append(a, [["another string", 3, 4]],axis = 0)

2 个答案:

答案 0 :(得分:2)

要拥有这样的混合数据类型数据,我们可以在追加或堆叠之前使用object作为dtype -

a = np.array([["String",1,2]], dtype=object)
b = [["another string", 3, 4]]
a = np.vstack((a,np.asarray(b,object)))

示例运行 -

In [40]: a = np.array([["String",1,2]], dtype=object)

In [41]: b = [["another string", 3, 4]]

In [42]: np.vstack((a,np.asarray(b,object)))
Out[42]: 
array([['String', 1, 2],
       ['another string', 3, 4]], dtype=object)

答案 1 :(得分:0)

当迭代地收集值时,通常最好在列表中收集它们,然后制作数组:

例如,使用您的数据制作一个列表:

In [371]: alist = [("String", 1, 2)]
In [372]: alist.append(("another string", 3, 4))
In [373]: alist
Out[373]: [('String', 1, 2), ('another string', 3, 4)]

出于多种目的,该列表非常有用,alist[0][i[0] for i in alist]

要制作列表,一个选项是结构化数组。因为我收集的值是我可以做的元组列表:

In [374]: np.array(alist, dtype='U20,int,int')
Out[374]: 
array([('String', 1, 2), ('another string', 3, 4)], 
      dtype=[('f0', '<U20'), ('f1', '<i4'), ('f2', '<i4')])
In [375]: _['f1']
Out[375]: array([1, 3])

我们按字段名称访问此类数组的fields。数组本身是1d,(2,)。

相反,我们制作一个object dtype数组:

In [376]: np.array(alist, dtype=object)
Out[376]: 
array([['String', 1, 2],
       ['another string', 3, 4]], dtype=object)
In [377]: _.shape
Out[377]: (2, 3)
In [378]: __[:,1]
Out[378]: array([1, 3], dtype=object)

有了这个,我们可以访问行和列。但请注意,我们不会通过对象数组获得快速计算优势,尤其是具有混合类型的对象数组。