在numpy中这样做的方法是使用structured array。
但是,在很多情况下,你使用的是异构数据,一个简单的python列表是一个更好的选择很多。 (或者,虽然这个答案写得并不广泛,但pandas.DataFrame
对于这种情况绝对是理想的。)
无论如何,上面给出的例子都可以作为“普通”numpy数组完美工作。您可以在您提供的示例中将所有内容都设置为浮动状态。 (一切似乎是一个int,除了浮体两列...的布尔变量可以容易地表示为整数。)
尽管如此,为了说明使用结构化dtypes ...
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', '<i8'), ('col1', '<i8'), ('col2', '<f8'), ('col3', '<f8'), ('col4', '<i8'), ('col5', '<i8'), ('col6', '|b1'), ('col7', '|b1'), ('col8', '<i8'), ('col9', '<i8'), ('col10', '<i8')])
有没有其他方法可以使用np.array? – dassouki 2010-09-16 14:33:08
你究竟想要做什么?我认为numpy可以加速数学运算:矩阵乘法,或者采用大量输入的余弦。不知道更多关于你在做什么,我只能提供一个常规的Python列表。 – mtrw 2010-09-16 14:38:43