改组结构化数组(记录数组)

时间:2014-04-03 09:13:16

标签: python arrays python-2.7 numpy structured-array

如何改组结构化数组。 numpy.random.shuffle似乎不起作用。此外,在以下示例中,只能对给定的字段x进行随机播放。

import numpy as np
data = [(1, 2), (3, 4.1), (13, 77), (5, 10), (11, 30)]
dtype = [('x', float), ('y', float)]
data1=np.array(data, dtype=dtype)
data1
>>> array([(1.0, 2.0), (3.0, 4.1), (13.0, 77.0), (5.0, 10.0), (11.0, 30.0)], 
      dtype=[('x', '<f8'), ('y', '<f8')])

np.random.seed(10)
np.random.shuffle(data)
data
>>> [(13, 77), (5, 10), (1, 2), (11, 30), (3, 4.1)]
np.random.shuffle(data1)
data1
>>> array([(1.0, 2.0), (3.0, 4.1), (1.0, 2.0), (3.0, 4.1), (1.0, 2.0)], 
      dtype=[('x', '<f8'), ('y', '<f8')])

我知道我可以明确地给出随机索引

data1[np.random.permutation(data1.shape[0])]

但我想要一个适当的洗牌。

2 个答案:

答案 0 :(得分:1)

这是由于一个numpy bug https://github.com/numpy/numpy/issues/4270Numpy 1.8.1中,这已得到解决。现在它按预期工作。

np.random.shuffle(data1)
data1
>>> array([(1.0, 2.0), (13.0, 77.0), (11.0, 30.0), (5.0, 10.0), (3.0, 4.1)], 
      dtype=[('x', '<f8'), ('y', '<f8')])

答案 1 :(得分:0)

numpy.random.shuffle支持多维数组。 见doc here。 doc上的示例表明您可以将多维数组作为参数传递。

所以我不知道为什么你的代码不起作用。

但还有另一种方法可以做到这一点。像:

shuffledIndex = random.shuffle(xrange(len(data)))
shuffledData = data[shuffledIndex]

糟糕...

import random
shuffledIndex = random.sample(xrange(len(data1)), len(data1))
shuffledData = data1[shuffledIndex]
相关问题