【问题标题】:how to convert a Series of arrays into a single matrix in pandas/numpy?如何将一系列数组转换为 pandas/numpy 中的单个矩阵?
【发布时间】:2017-04-11 00:17:53
【问题描述】:

我不知何故得到了一个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) 的矩阵?谢谢!

【问题讨论】:

  • 你为什么要经历一个系列?如果这是您想要的,为什么不直接转换为矩阵?
  • import numpy as np; np.array(data) 怎么样?您可能不需要创建Series。另外,请注意(11,3) 维度最好用DataFrame 表示。
  • 你的系列包含列表,而不是数组。
  • @Abdou 你甚至不需要reshape,只需np.array(data) 就可以了。

标签: python pandas matrix multidimensional-array series


【解决方案1】:

我用 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

【讨论】:

    【解决方案2】:

    如果由于某种原因,您发现自己对 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)
    

    但除非是你无法改变的东西,否则一开始就拥有那个系列毫无意义。

    【讨论】:

    • 谢谢,我有一个由一系列行组成的 pandas 系列,这有助于我从 (m, 1) 转换为适当的数组维度 (m,n)
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      np.stack(s.values)
      

      PS。我经常遇到类似的情况。

      【讨论】:

      • 这个。请这是答案。
      • 这是要走的路。其他方法在 750GB RAM 机器上耗尽内存。
      • 适用于附加在一系列 (1000,) -> (1000, 128, 128, 3) 中的多维数组
      猜你喜欢
      • 2016-08-26
      • 2015-04-30
      • 2014-12-19
      • 2018-07-25
      • 2021-07-22
      • 2012-08-28
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      相关资源
      最近更新 更多