[英]Python Library for Multivariate Dynamic Time Warping - Clustering Multiple Series
[英]Create an array of arrays from a dataframe with multiple multivariate time series in Python
我需要從 dataframe 創建一個 arrays 數組:
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
變量是來自每個患者的每個數據子序列的 label。 每個患者的塊的長度是可變的。 我需要以這樣的數組結束:
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 package 中使用它進行多變量時間序列聚類。 任何幫助是極大的贊賞。
我想你正在尋找這個:
arr = df.set_index('ID').groupby('ID').apply(pd.DataFrame.to_numpy).to_numpy()
與您的解決方案類似,首先 groupby 然后使用 to_numpy 將它們轉換為 arrays。 請注意,如果您的 arrays 具有不同的形狀(即不同的 ID 長度),則不能使用非矩形 numpy arrays。 因此,此代碼返回您要查找的 arrays 數組。
output:
[array([[101. , 51. , 81. , 37.1],
[102. , 52. , 82. , 37.2],
[103. , 53. , 83. , 37.3],
[104. , 54. , 84. , 37.4],
[105. , 55. , 85. , 37.5]])
array([[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]])
...
array([[100., 50., 75., 37.],
[100., 50., 75., 37.]])
...
array([[100., 50., 60., 37.],
[100., 50., 60., 37.],
[100., 50., 60., 37.],
[100., 50., 60., 37.],
[100., 50., 60., 37.]])]
如果所有'ID'
的行數相同,則可以堆疊上面的 numpy 數組arr
以獲得單個數組:
np.stack(arr)
[[[101. 51. 81. 37.1]
[102. 52. 82. 37.2]
[103. 53. 83. 37.3]
[104. 54. 84. 37.4]
[105. 55. 85. 37.5]]
[[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. ]
[100. 50. 60. 37. ]
[100. 50. 60. 37. ]
[100. 50. 60. 37. ]
[100. 50. 60. 37. ]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.