python- numpy阵列中的字符串和整数



我想创建一个带有3列的数组。第一个是字符串,其他两个整数用于计算。然后,将通过附录函数(下(添加更多的行。

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

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

要拥有如此混合的数据类型数据,我们可以在附加或堆叠之前使用 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)

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

例如,与您的数据一起列出列表:

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)

这样,我们可以访问行和列。但是请当心我们不会从对象数组中获得快速的numpy计算益处,尤其是一个混合类型的对象。

最新更新