如何在 pandas/numpy 中将一系列数组转换为单个矩阵?

how to convert a Series of arrays into a single matrix in pandas/numpy?

我以某种方式得到了一个 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,)

如何将 s 转换为形状为 (11,3) 的矩阵?谢谢!

如果,由于某种原因,你发现自己对 Series 感到厌恶,那么把它变回你想要的那种 matrixarray 很简单:

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.array(s.tolist())

In [18]: sm
Out[18]:
array([[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)

但是,除非它是您无法改变的东西,否则从一开始就没有什么意义。

另一种方法是提取系列的值并在其上使用 numpy.stack。

np.stack(s.values)

PS。我 运行 经常遇到类似情况。

对于pandas>=0.24,您还可以np.stack(s.to_numpy())np.concatenate(s.to_numpy()),具体取决于您的要求。

我用 5793 个 100D 向量测试了上述方法。旧方法首先转换为列表,速度最快。

%time print(np.stack(df.features.values).shape)
%time print(np.stack(df.features.to_numpy()).shape)
%time print(np.array(df.features.tolist()).shape)
%time print(np.array(list(df.features)).shape)

结果

(5793, 100)
CPU times: user 11.7 ms, sys: 3.42 ms, total: 15.1 ms
Wall time: 22.7 ms
(5793, 100)
CPU times: user 11.1 ms, sys: 137 µs, total: 11.3 ms
Wall time: 11.9 ms
(5793, 100)
CPU times: user 5.96 ms, sys: 0 ns, total: 5.96 ms
Wall time: 6.91 ms
(5793, 100)
CPU times: user 5.74 ms, sys: 0 ns, total: 5.74 ms
Wall time: 6.43 ms