gpt4 book ai didi

python - 转换数据文件 'X' 'Y' 'Z' 'data' 格式

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:44 25 4
gpt4 key购买 nike

我有 3 个数据集,第一个名为 Data 的保存我的数据;该表有 5 列和 3 行 - 每列代表一个特定的位置,可以用一组 X、Y 位置来标识,每行代表一个特定的深度 (Z);第二个数据集包含 5 个 X、Y 位置(第一个数据集的列),而第三个文件包含 3 个 Z 值,(数据表的行)

生成我的数据

import numpy as np 
Data = np.arange(1, 16).reshape(3, 5) #holds the 'data' I am interested in
X = [0, 0, 1, 1, 2] #create 'X', 'Y' values
Y = [0, 1, 0, 1, 0]
XY = np.array((X, Y)).reshape(5, 2) # this is the format I have the 'X' and 'Y' values
Z = [-1, -5, -10]
z = np.array(Z)

我现在想合并所有并拥有一个新的 X、Y、Z、数据格式的 numpy 数组(或 pandas 数据框)例如,对于给定表的前 3 行的数据应该是:

X Y  Z Data #this is a header, I just add it to make reading easier
0 0 -1 1
0 0 -5 6
0 0 -10 11
0 1 -1 2
0 1 -5 7
0 1 -10 12

等....

任何关于如何做到这一点的提示都会很棒我正在考虑使用 pandas 创建适当的(多)索引列,但我找不到合适的方法

最佳答案

从 X 和 Y 构建一个 MultiIndex,并使用 unstack。

In [4]: columns = pd.MultiIndex.from_arrays([X, Y])

In [5]: df = DataFrame(Data, columns=columns, index=Z)

In [6]: df
Out[6]:
0 1 2
0 1 0 1 0
-1 1 2 3 4 5
-5 6 7 8 9 10
-10 11 12 13 14 15

In [7]: df1 = df.unstack().reset_index()

In [8]: df1.columns = ['X', 'Y', 'Z', 'Data']

In [9]: df1
Out[9]:
X Y Z Data
0 0 0 -1 1
1 0 0 -5 6
2 0 0 -10 11
3 0 1 -1 2
4 0 1 -5 7
5 0 1 -10 12
6 1 0 -1 3
7 1 0 -5 8
8 1 0 -10 13
9 1 1 -1 4
10 1 1 -5 9
11 1 1 -10 14
12 2 0 -1 5
13 2 0 -5 10
14 2 0 -10 15

我选择制作 X、Y 和 Z 适当的列 (reset_index()),而不是将它们保留为三级 MultiIndex。通常,这更清洁且更有用。

关于python - 转换数据文件 'X' 'Y' 'Z' 'data' 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19363144/

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