我正在尝试从np数组中插入尺寸为(24,12)的72个矩阵到预先存在的MultiIndexDataFrame中,该索引根据尺寸为(72,2)的np.array进行索引。我不在乎为矩阵的内容建立索引(24,12),我只需要为72个矩阵建立索引,甚至可以将它们作为对象进行重新排列。就像一张地图,在某些情况下需要重新排序以重新堆积列。
到目前为止我尝试过的是:
cosphi.shape
(72,2)
MFPAD_RCR.shape
(72,24,12)
df = pd.MultiIndex.from_arrays(cosphi.T, names=("costheta","phi"))
我成功创建了一个具有72个索引行的2列的DataFrame。然后我尝试添加72个矩阵
df1 = pd.DataFrame({'MFPAD':MFPAD_RCR},index=df)
或可能
df1 = pd.DataFrame({'MFPAD':MFPAD_RCR.astype(object)},index=df)
我得到了错误
Exception: Data must be 1-dimensional.
有什么主意吗?
答案 0 :(得分:0)
经过一番仔细研究之后,我发现我的问题has been already answered here(正确的答案)和here(使用不推荐使用的功能的解决方案)。
对于我的具体问题,答案类似于:
data = MFPAD_RCR.reshape(72, 288).T
df = pd.DataFrame(
data=data,
index=pd.MultiIndex.from_product([phiM, cosM],names=["phi","cos(theta)"]),
columns=['item {}'.format(i) for i in range(72)]
)
请注意:3D np数组必须以第二维等于主索引和次索引的乘积来整形。
df1 = df.T
我希望能够根据来自cosphi的额外索引对项目(又称矩阵)进行排序
cosn=np.array([col[0] for col in cosphi]); #list
phin=np.array([col[1] for col in cosphi]); #list
注意:新索引的长度必须与项目(矩阵)= 72相同
df1.set_index(cosn, "cos_ph", append=True, inplace=True)
df1.set_index(phin, "phi_ph", append=True, inplace=True)
这之后可以排序
df1.sort_index(level=1, inplace=True, kind="mergesort")
并重塑
outarray=(df1.T).values.reshape(24,12,72).transpose(2, 0, 1)
任何建议使代码更快/更漂亮的建议都值得欢迎!