gpt4 book ai didi

python - 使用 pandas 写入和读取 3D 数据

转载 作者:行者123 更新时间:2023-11-28 22:22:16 25 4
gpt4 key购买 nike

我有一个项目使用保存在文本文件中的 3D 数据。我目前使用一个空格来拆分第一维的数据,一个换行符 (\n) 来拆分第二维,两个换行符 (\n\n) 来拆分最后一个维度,并且使用默认的读写 python 。这些数据的解释是使用字符串拆分和列表理解来完成的。 有没有办法使用 pandas 做到这一点?

我已经使用 3D numpy 数据测试了 dataframe.write 并得到以下错误:ValueError:必须通过二维输入。是否可以解决此问题?

最佳答案

Pandas 拥有一个 Panel 类来管理 3D 数组,并将它们表示为未堆叠的数据帧。然而,需要一些轴转换才能在文本文件中具有正确的布局:

a=arange(27).reshape(3,3,3)

array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],

[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],

[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])

写作:

df=pd.Panel(np.rollaxis(a,2)).to_frame()
df.to_csv('datap.txt')

然后文本文件包含:

major,minor,0,1,2
0,0,0,1,2
0,1,3,4,5
0,2,6,7,8
1,0,9,10,11
1,1,12,13,14
1,2,15,16,17
2,0,18,19,20
2,1,21,22,23
2,2,24,25,26

您还可以使用 to_html 来增强可读性:

enter image description here

然后你可以回读:

#read
df=pd.read_csv('datap.txt',index_col=[0,1])
a2= np.rollaxis(np.rollaxis(df.to_panel().values,2),2)

In [161]: np.allclose(a,a2)
Out[161]: True

但将来您将不得不为此使用 xarray 模块。

关于python - 使用 pandas 写入和读取 3D 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47799925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com