我有一个 3 维 numpy
数组,(z, x, y)
. z
是时间维度和 x
和 y
是坐标。
我想将其转换为多索引 pandas.DataFrame
.我希望行索引是 z 维度
并且每列都具有来自唯一 x、y 坐标的值(因此,每列都将是多索引的)。
最简单的情况(不是多索引):
>>> array.shape
(500L, 120L, 100L)
>>> df = pd.DataFrame(array[:,0,0])
>>> df.shape
(500, 1)
我一直在尝试使用 pd.MultiIndex.from_arrays 将整个数组传递到多索引数据帧中,但出现错误:
NotImplementedError: > 1 ndim Categorical 目前不支持
看起来它应该相当简单,但我无法弄清楚。
最佳答案
我发现一个 Series with a Multiindex是具有任意多维(大概是 3 个或更多)的 numpy 数组的最类似的 Pandas 数据类型。
这是一些示例代码:
import pandas as pd
import numpy as np
time_vals = np.linspace(1, 50, 50)
x_vals = np.linspace(-5, 6, 12)
y_vals = np.linspace(-4, 5, 10)
measurements = np.random.rand(50,12,10)
#setup multiindex
mi = pd.MultiIndex.from_product([time_vals, x_vals, y_vals], names=['time', 'x', 'y'])
#connect multiindex to data and save as multiindexed Series
sr_multi = pd.Series(index=mi, data=measurements.flatten())
#pull out a dataframe of x, y at time=22
sr_multi.xs(22, level='time').unstack(level=0)
#pull out a dataframe of y, time at x=3
sr_multi.xs(3, level='x').unstack(level=1)
关于python-2.7 - 3 维 numpy 数组到多索引 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43427189/