繁体   English   中英

将具有 n 级分层索引的 Pandas DataFrame 转换为 nD Numpy 数组

[英]Transform Pandas DataFrame with n-level hierarchical index into n-D Numpy array

有没有一种好方法可以将具有n级索引的 DataFrame 转换为n -D Numpy 数组(又名n -张量)?


例子

假设我设置了一个 DataFrame 像

from pandas import DataFrame, MultiIndex

index = range(2), range(3)
value = range(2 * 3)
frame = DataFrame(value, columns=['value'],
                  index=MultiIndex.from_product(index)).drop((1, 0))
print frame

哪个输出

     value
0 0      0
  1      1
  2      3
1 1      5
  2      6

该索引是一个 2 级分层索引。 我可以使用从数据中提取二维 Numpy 数组

print frame.unstack().values

哪个输出

[[  0.   1.   2.]
 [ nan   4.   5.]]

这如何推广到n级索引?

玩弄unstack() ,好像只能用来按摩DataFrame的二维形状,不能加轴。

我不能使用例如frame.values.reshape(x, y, z) ,因为这将要求框架包含准确的x * y * z行,这是无法保证的。 这就是我在上面的例子中试图通过drop()一行来演示的。

任何建议都非常感谢。

编辑 这种方法比我在下面给出的方法更优雅(并且快两个数量级)。

# create an empty array of NaN of the right dimensions
shape = map(len, frame.index.levels)
arr = np.full(shape, np.nan)

# fill it using Numpy's advanced indexing
arr[frame.index.codes] = frame.values.flat
# ...or in Pandas < 0.24.0, use
# arr[frame.index.labels] = frame.values.flat

原始解决方案 给定类似于上面的设置,但在 3-D 中,

from pandas import DataFrame, MultiIndex
from itertools import product

index = range(2), range(2), range(2)
value = range(2 * 2 * 2)
frame = DataFrame(value, columns=['value'],
                  index=MultiIndex.from_product(index)).drop((1, 0, 1))
print(frame)

我们有

       value
0 0 0      0
    1      1
  1 0      2
    1      3
1 0 0      4
  1 0      6
    1      7

现在,我们继续使用reshape()路线,但进行一些预处理以确保沿每个维度的长度保持一致。

首先,使用所有维度的完整笛卡尔积重新索引数据框。 NaN值将根据需要插入。 此操作可能既慢又消耗大量内存,具体取决于维数和数据帧的大小。

levels = map(tuple, frame.index.levels)
index = list(product(*levels))
frame = frame.reindex(index)
print(frame)

哪个输出

       value
0 0 0      0
    1      1
  1 0      2
    1      3
1 0 0      4
    1    NaN
  1 0      6
    1      7

现在, reshape()将按预期工作。

shape = map(len, frame.index.levels)
print(frame.values.reshape(shape))

哪个输出

[[[  0.   1.]
  [  2.   3.]]

 [[  4.  nan]
  [  6.   7.]]]

(相当丑陋的)单线是

frame.reindex(list(product(*map(tuple, frame.index.levels)))).values\
     .reshape(map(len, frame.index.levels))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM