[英]How do I store mutidimensional arrays contained in a dictionary in a python xarray?
我有一本字典,其中包含各种大小的numpy
服装。 所有数组都有一个共同的轴长(时间),我希望将其存储在其中。
例如:
arr1 = np.random.rand(239, 1)
arr2 = np.random.rand(239, 6)
arr3 = np.random.rand(239, 3, 7)
time = np.random.rand(239, 1)
d = {'A': arr1, 'B': arr2, 'C': arr3, 'time': time}
我需要能够轻松地索引和操作数据,所以我的第一个倾向是使用pandas.Panel
存储数据,但是由于尺寸不一致,我一直没有成功。
xarray.Dataset
是在此处存储我的数据的正确方法吗?如果可以的话,如何最好地实现呢?
这是使用标准熊猫方法的一种非常简单的方法。 为了简便起见,我将数据缩小并放入数据框,但是概念是相同的。
dr=pd.date_range('1-1-2017', periods=4, freq='d')
df1=pd.DataFrame( np.random.randn(4), columns=['x'], index=dr)
df2=pd.DataFrame( np.random.randn(4,2), columns=['y','z'], index=dr)
所以df1
和df2
看起来像这样:
x
2017-01-01 -0.705449
2017-01-02 -0.597631
2017-01-03 -0.844197
2017-01-04 -1.063895
y z
2017-01-01 -0.288822 -0.343934
2017-01-02 1.072678 1.776767
2017-01-03 -0.606593 0.192280
2017-01-04 0.019401 2.007770
像这样重新配置:
df = df1.stack().append(df2.stack()).sort_index()
2017-01-01 x -0.705449
y -0.288822
z -0.343934
2017-01-02 x -0.597631
y 1.072678
z 1.776767
2017-01-03 x -0.844197
y -0.606593
z 0.192280
2017-01-04 x -1.063895
y 0.019401
z 2.007770
您甚至可以使用以下命令从此处转换为xarray
:
df.to_xarray()
快速注意事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.