34

I'm using pandas.Series and np.ndarray.

The code is like this

>>> t
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> pandas.Series(t)
Exception: Data must be 1-dimensional
>>>

And I trie to convert it into 1-dimensional array:

>>> tt = t.reshape((1,-1))
>>> tt
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

tt is still multi-dimensional since there are double '['.

So how do I get a really convert ndarray into array?

After searching, it says they are the same. However in my situation, they are not working the same.

4

3 回答 3

36

另一种方法是使用np.ravel

>>> np.zeros((3,3)).ravel()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

ravelover的重要性flatten在于ravel仅在必要时复制数据并通常返回一个视图,而flatten将始终返回数据的副本。

要使用 reshape 来展平数组:

tt = t.reshape(-1)
于 2013-08-13T03:17:12.090 回答
5

使用.flatten

>>> np.zeros((3,3))
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> _.flatten()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

编辑:正如所指出的,这在每种情况下都会返回输入的副本。为避免复制,.ravel请按照@Ophion 的建议使用。

于 2013-08-13T03:14:13.697 回答
1
tt = array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

oneDvector = tt.A1

这是解决双括号问题的唯一方法,即转换为 nd 矩阵的一维数组。

于 2017-05-16T04:56:57.143 回答