【问题标题】:Convert numpy array with indices to a pandas dataframe将带有索引的 numpy 数组转换为 pandas 数据框
【发布时间】:2018-02-01 23:58:38
【问题描述】:

我有一个 numpy 数组,我想用 python ggplot's tile 打印它。为此,我需要一个包含 x、y、值列的 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

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案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
    

    性能

    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
    

    【讨论】:

    • 我试图澄清我想要的问题。我不确定你的回答有什么帮助。
    • 你的第一个答案有效,你的第二个答案抛出ValueError: Shape of passed values is (3, 6), indices imply (3, 3)
    • @Make42 复制粘贴错误。必须包括columns=。它有效。
    • @Make42 有趣的是,速度方面它们几乎相同。这是您想要使用的偏好问题。
    • 但是他们做的不完全一样吗?那么这与偏好有什么关系呢?
    猜你喜欢
    • 2016-03-31
    • 2020-06-20
    • 1970-01-01
    • 2022-01-12
    • 2016-11-20
    • 2018-02-27
    • 2014-03-23
    相关资源
    最近更新 更多