python - 将带有索引的 numpy 数组转换为 pandas 数据框

标签 python pandas numpy dataframe

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

澄清我想要什么:

我从像这样的 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

最佳答案

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

关于python - 将带有索引的 numpy 数组转换为 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45855904/

相关文章:

python - 外键模型的django计数

python - 基于列重复 DataFrame 中的行

python - 在 Pandas 中将嵌套 JSON 数据作为数据帧访问

python - 类型错误 : object of type 'numpy.int64' has no len()

python - 如何在 pandas Dataframe 中查找 numpy 数组列的 boolean 值?

python - Django迁移: all the columns are not generated as the model

python - 函数似乎返回多个结果或 : what is implicit tuple unpacking

python - booleans().example() 总是返回 True

python - 如何在python中的groupby中为lambda函数设置名称 header

python - 如何在 python 中将平面列表转换为二维数组?