首页 文章

将带索引的numpy数组转换为pandas数据帧

提问于
浏览
0

我有一个numpy数组,我想用python ggplot's tile打印 . 为此,我需要一个包含x,y,value列的DataFrame . 如何将numpy数组有效地转换为这样的DataFrame . 请考虑,我想要的数据形式是稀疏样式,但我想要一个常规的DataFrame . 我尝试使用像Convert sparse matrix (csc_matrix) to pandas dataframe这样的scipy稀疏数据结构,但是转换太慢而且内存很耗尽:我的内存已用完了 .

澄清我想要的东西:

我从一个像numpy数组开始

array([[ 1,  3,  7],
       [ 4,  9,  8]])

我想最终得到DataFrame

x    y    value
0    0    0    1
1    0    1    3
2    0    2    7
3    1    0    4
4    1    1    9
5    1    2    8

1 回答

  • 1
    arr = np.array([[1, 3, 7],
                    [4, 9, 8]])
    
    df = pd.DataFrame(np.hstack((np.indices(arr.shape).reshape(2, arr.size).T,\
                        arr.reshape(-1, 1))), columns=['x', 'y', 'value'])
    print(df)
    
       x  y  value
    0  0  0      1
    1  0  1      3
    2  0  2      7
    3  1  0      4
    4  1  1      9
    5  1  2      8
    

    您也可以考虑使用this中使用的函数,作为上述解决方案中 np.indices 的加速:

    def indices_merged_arr(arr):
        m,n = arr.shape
        I,J = np.ogrid[:m,:n]
        out = np.empty((m,n,3), dtype=arr.dtype)
        out[...,0] = I
        out[...,1] = J
        out[...,2] = arr
        out.shape = (-1,3)
        return out
    
    array = np.array([[ 1,  3,  7],
                      [ 4,  9,  8]])
    
    df = pd.DataFrame(indices_merged_arr(array), columns=['x', 'y', 'value'])
    print(df)
    
       x  y  value
    0  0  0      1
    1  0  1      3
    2  0  2      7
    3  1  0      4
    4  1  1      9
    5  1  2      8
    

    Performance

    arr = np.random.randn(1000, 1000)
    
    %timeit df = pd.DataFrame(np.hstack((np.indices(arr.shape).reshape(2, arr.size).T,\
                             arr.reshape(-1, 1))), columns=['x', 'y', 'value'])
    100 loops, best of 3: 15.3 ms per loop
    
    %timeit pd.DataFrame(indices_merged_arr(array), columns=['x', 'y', 'value'])
    1000 loops, best of 3: 229 µs per loop
    

相关问题