如何在 Pandas/numpy 中将一系列数组转换为单个矩阵?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40824601/
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 a Series of arrays into a single matrix in pandas/numpy?
提问by user3768495
I somehow got a pandas.Serieswhich contains a bunch of arrays in it, as the sin the code below.
我不知何故得到了一个pandas.Series,其中包含一堆数组,如s下面的代码所示。
data = [[1,2,3],[2,3,4],[3,4,5],[2,3,4],[3,4,5],[2,3,4],
[3,4,5],[2,3,4],[3,4,5],[2,3,4],[3,4,5]]
s = pd.Series(data = data)
s.shape # output ---> (11L,)
# try to convert s to matrix
sm = s.as_matrix()
# but...
sm.shape # output ---> (11L,)
How can I convert the sinto a matrix with shape (11,3)? Thanks!
如何将其s转换为形状为 (11,3) 的矩阵?谢谢!
回答by Selah
Another way is to extract the values of your series and use numpy.stack on them.
另一种方法是提取系列的值并在它们上使用 numpy.stack 。
np.stack(s.values)
PS. I've run into similar situations often.
附注。我经常遇到类似的情况。
回答by juanpa.arrivillaga
If, for some reason, you have found yourself with that abomination of a Series, getting it back into the sort of matrixor arrayyou want is straightforward:
如果由于某种原因,您发现自己讨厌 a Series,那么将其恢复为您想要的那种matrix或array您想要的很简单:
In [16]: s
Out[16]:
0 [1, 2, 3]
1 [2, 3, 4]
2 [3, 4, 5]
3 [2, 3, 4]
4 [3, 4, 5]
5 [2, 3, 4]
6 [3, 4, 5]
7 [2, 3, 4]
8 [3, 4, 5]
9 [2, 3, 4]
10 [3, 4, 5]
dtype: object
In [17]: sm = np.matrix(s.tolist())
In [18]: sm
Out[18]:
matrix([[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[2, 3, 4],
[3, 4, 5],
[2, 3, 4],
[3, 4, 5],
[2, 3, 4],
[3, 4, 5],
[2, 3, 4],
[3, 4, 5]])
In [19]: sm.shape
Out[19]: (11, 3)
But unless it's something you can't change, having that Series makes little sense to begin with.
但除非它是你无法改变的东西,否则拥有该系列一开始就毫无意义。
回答by Tengerye
For the pandas>=0.24, you can also np.stack(s.to_numpy())or np.concatenate(s.to_numpy()), depending on your requirement.
对于 pandas>=0.24,您也可以np.stack(s.to_numpy())或np.concatenate(s.to_numpy()),具体取决于您的要求。

