【问题标题】:Convert list of arrays to pandas dataframe将数组列表转换为熊猫数据框
【发布时间】:2023-03-30 14:37:01
【问题描述】:

我有一个要转换为 DataFrame 的 numpy 数组列表。每个数组应该是数据框的一行。

使用 pd.DataFrame() 不起作用。它总是给出错误:ValueError: Must pass 2-d input。

有没有更好的方法来做到这一点?

这是我当前的代码:

list_arrays = [ array([[0, 0, 0, 1, 0, 0, 0, 0, 00]], dtype='uint8'), 
                array([[0, 0, 3, 2, 0, 0, 0, 0, 00]], dtype='uint8')
              ]

d = pd.DataFrame(list_arrays)

ValueError: Must pass 2-d input

【问题讨论】:

    标签: python python-3.x pandas numpy dataframe


    【解决方案1】:

    您可以使用pd.Series

    pd.Series(l).apply(lambda x : pd.Series(x[0]))
    Out[294]: 
       0  1  2  3  4  5  6  7  8
    0  0  0  0  1  0  0  0  0  0
    1  0  0  3  2  0  0  0  0  0
    

    【讨论】:

      【解决方案2】:

      选项 1:

      In [143]: pd.DataFrame(np.concatenate(list_arrays))
      Out[143]:
         0  1  2  3  4  5  6  7  8
      0  0  0  0  1  0  0  0  0  0
      1  0  0  3  2  0  0  0  0  0
      

      选项 2:

      In [144]: pd.DataFrame(list(map(np.ravel, list_arrays)))
      Out[144]:
         0  1  2  3  4  5  6  7  8
      0  0  0  0  1  0  0  0  0  0
      1  0  0  3  2  0  0  0  0  0
      

      我为什么会得到:

      ValueError: Must pass 2-d input

      我认为pd.DataFrame() 尝试将其转换为 NDArray,如下所示:

      In [148]: np.array(list_arrays)
      Out[148]:
      array([[[0, 0, 0, 1, 0, 0, 0, 0, 0]],
      
             [[0, 0, 3, 2, 0, 0, 0, 0, 0]]], dtype=uint8)
      
      In [149]: np.array(list_arrays).shape
      Out[149]: (2, 1, 9)     # <----- NOTE: 3D array
      

      【讨论】:

      • 谢谢!所有这些都有效。但我想知道为什么我会收到那个二维错误。
      • 对我来说,pd.DataFrame(np.concatenate(list_arrays)) 只是让我的所有数组变平并成为一维数组,而不是“行堆叠”它们。因此,我建议只使用 pd.DataFrame(np.row_stack(list_arrays)) 。在 140k 行 x 17k 列上花了几秒钟
      【解决方案3】:

      替代 1

      pd.DataFrame(sum(map(list, list_arrays), []))
      
         0  1  2  3  4  5  6  7  8
      0  0  0  0  1  0  0  0  0  0
      1  0  0  3  2  0  0  0  0  0
      

      替代 2

      pd.DataFrame(np.row_stack(list_arrays))
      
         0  1  2  3  4  5  6  7  8
      0  0  0  0  1  0  0  0  0  0
      1  0  0  3  2  0  0  0  0  0
      

      【讨论】:

        【解决方案4】:

        这是一种方法。

        import numpy as np, pandas as pd
        
        lst = [np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0]], dtype=int),
               np.array([[0, 0, 3, 2, 0, 0, 0, 0, 0]], dtype=int)]
        
        df = pd.DataFrame(np.vstack(lst))
        
        #    0  1  2  3  4  5  6  7  8
        # 0  0  0  0  1  0  0  0  0  0
        # 1  0  0  3  2  0  0  0  0  0
        

        【讨论】:

          猜你喜欢
          • 2019-10-12
          • 2017-08-26
          • 2020-07-15
          • 1970-01-01
          • 1970-01-01
          • 2018-08-25
          • 2014-08-02
          • 2017-12-12
          相关资源
          最近更新 更多