【发布时间】:2020-09-29 07:03:22
【问题描述】:
我需要从数据框创建一个数组数组:
HR sBP dBP T ID
101 51 81 37.1 P1.1
102 52 82 37.2 P1.1
103 53 83 37.3 P1.1
104 54 84 37.4 P1.1
105 55 85 37.5 P1.1
210 65 90 36.1 P1.2
210 65 90 36.2 P1.2
210 65 90 36.3 P1.2
210 65 90 36.4 P1.2
210 65 90 36.5 P1.2
...
100 50 75 37 Pm.n
100 50 75 37 Pm.n
...
100 50 60 37.0 P1500.6
100 50 60 37.0 P1500.6
100 50 60 37.0 P1500.6
100 50 60 37.0 P1500.6
100 50 60 37.0 P1500.6
其中每个块是一个多元时间序列,其中 HR、sBP、dBP 和 T° 作为变量,ID 变量是来自每个患者的每个数据子序列的标签。每个患者的块的长度是可变的。
我需要得到一个这样的数组:
array([[[101, 51, 81, 37.1],
[102, 52, 82, 37.2],
[103, 53, 83, 37.2],
[104, 54, 84, 37.2],
[105, 55, 85, 37.2]],
[[210, 65, 90, 36.1],
[210, 65, 90, 36.2],
[210, 65, 90, 36.3],
[210, 65, 90, 36.4],
[210, 65, 90, 36.5]],
...
[[100, 50, 60, 37.0],
[100, 50, 60, 37.0],
[100, 50, 60, 37.0],
[100, 50, 60, 37.0],
[100, 50, 60, 37.0]]])
array.shape = (number of unique IDs, length of arrays, number of dimensions)
我的代码如下所示:
df_grp = df.groupby('ID')
for name, gp in df_grp:
if name == 'P1.1':
arr = gp.drop(columns = ['ID']).to_numpy().reshape(-1,4)
else:
temp_arr = gp.drop(columns = ['ID']).to_numpy().reshape(-1,4)
arr = np.append(arr, temp_arr, axis=0)
但它给了我一个这样的数组
array ([[101, 51, 81, 37.1],
[102, 52, 82, 37.2],
[103, 53, 83, 37.2],
[104, 54, 84, 37.2],
[105, 55, 85, 37.2],
[210, 65, 90, 36.1],
[210, 65, 90, 36.2],
[210, 65, 90, 36.3],
[210, 65, 90, 36.4],
[210, 65, 90, 36.5]],
...
[100, 50, 60, 37.0],
[100, 50, 60, 37.0],
[100, 50, 60, 37.0],
[100, 50, 60, 37.0],
[100, 50, 60, 37.0]])
array.shape = (number of rows in df, number of dimensions)。不管有没有reshape,结果都是一样的,squeeze也是一样。
我需要上述格式的数组,以便可以在 tslearn 包中使用它进行多变量时间序列聚类。
非常感谢任何帮助。
【问题讨论】:
标签: python pandas numpy time-series