Python-Numpy数组中的字符串和整数 [英] Python - strings and integers in Numpy array

查看:538
本文介绍了Python-Numpy数组中的字符串和整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create an array with 3 columns. The first one a string, the other two integers used for calculations. Then more rows will be added through the append function (below).

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

The problem is that all columns seem to be coded as strings rather than just the first one. How do I get the correct data type for the numbers?

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

推荐答案

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

To have such a mixed datatype data, we could use object as dtype before appending or stacking -

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)

这篇关于Python-Numpy数组中的字符串和整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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