Python 如何将ndarray转换为数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18200052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert ndarray to array?
提问by SolessChong
I'm using pandas.Series and np.ndarray.
我正在使用 pandas.Series 和 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 '['.
tt 仍然是多维的,因为有双 '['。
So how do I get a really convert ndarray into array?
那么如何才能真正将 ndarray 转换为数组呢?
After searching, it says they are the same. However in my situation, they are not working the same.
搜索后,它说它们是相同的。但是,在我的情况下,它们的工作方式不同。
采纳答案by Daniel
An alternative is to use np.ravel:
另一种方法是使用np.ravel:
>>> np.zeros((3,3)).ravel()
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0.])
The importance of ravel
over flatten
is ravel
only copies data if necessary and usually returns a view, while flatten
will always return a copy of the data.
ravel
over的重要性flatten
是ravel
只在必要时复制数据,通常返回一个视图,而flatten
总是返回数据的副本。
To use reshape to flatten the array:
要使用 reshape 来展平数组:
tt = t.reshape(-1)
回答by nneonneo
Use .flatten
:
使用.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.])
EDIT: As pointed out, this returns a copy of the input in every case. To avoid the copy, use .ravel
as suggested by @Ophion.
编辑:正如所指出的,这在每种情况下都会返回输入的副本。为避免复制,请.ravel
按照@Ophion 的建议使用。
回答by Jemshid KK
tt = array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
oneDvector = tt.A1
This is the only approach which solved the problem of double brackets, that is conversion to 1D array that nd matrix.
这是解决双括号问题的唯一方法,即转换为 nd 矩阵的一维数组。