python中每个对象都有一个数据类型_指定python numpy数组中每个对象的数据类型

在numpy中这样做的方法是使用structured array。

然而,在许多使用异构数据的情况下,一个简单的python列表是一个更好的选择。(或者,尽管在编写这个答案时它并不广泛可用,但是pandas.DataFrame对于这个场景来说绝对是理想的。)

无论如何,上面给出的示例将作为一个“普通”numpy数组完美地工作。在你给出的例子中,你可以把所有的东西都变成浮子。(除了两列浮点数外,所有内容都是int。。。bools可以很容易地表示为int。)

尽管如此,为了说明如何使用结构化数据类型。。。import numpy as np

ua = 5 # No idea what "ua" is in your code above...

low_inc, med_inc = 0.5, 2.0 # Again, no idea what these are...

num = 100

num_fields = 11

# Use more descriptive names than "col1"! I'm just generating the names as placeholders

dtype = {'names':['col%i'%i for i in range(num_fields)],

'formats':2*[np.int] + 2*[np.float] + 2*[np.int] + 2*[np.bool] + 3*[np.int]}

data = np.zeros(num, dtype=dtype)

# Being rather verbose...

data['col0'] = np.arange(num, dtype=np.int)

data['col1'] = int(ua) * np.ones(num)

data['col2'] = np.random.uniform(low_inc / 2, med_inc * 2, num)

data['col3'] = np.random.uniform(0, 6, num)

data['col4'] = np.random.randint(100, 5000, num)

data['col5'] = np.random.randint(100, 500, num)

data['col6'] = np.random.randint(0, 2, num).astype(np.bool)

data['col7'] = np.random.randint(0, 2, num).astype(np.bool)

data['col8'] = np.random.randint(100, 5000, num)

data['col9'] = np.random.randint(100, 5000, num)

data['col10'] = np.random.randint(100, 5000, num)

print data

它产生一个包含11个字段的100元素数组:array([ (0, 5, 2.0886534380436226, 3.0111285613794276, 3476, 117, False, False, 4704, 4372, 4062),

(1, 5, 2.0977199579338115, 1.8687472941590277, 4635, 496, True, False, 4079, 4263, 3196),

...

...

(98, 5, 1.1682309811443277, 1.4100766819689299, 1213, 135, False, False, 1250, 2534, 1160),

(99, 5, 1.746554619056416, 5.210411489007637, 1387, 352, False, False, 3520, 3772, 3249)],

dtype=[('col0', '

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值