我有一個長陣列(可以是 pandas 或 numpy,為方便起見),其中某些行的前兩列相同(xy 位置),第三列是唯一的(時間),例如:
x y t
0. 0. 10.
0. 0. 11.
0. 0. 12.
0. 1. 13.
0. 1. 14.
1. 1. 15.
位置是分組的,但每個位置可能列出 1、2 或 3 個時間值,這意味著可能有 1、2 或 3 列具有相同的 x 和 y。陣列需要重新整形/壓縮,以便每個位置都有自己的行,具有時間的最小值和最大值 - 即,目標是:
x y t1 t2
0. 0. 10. 12.
0. 1. 13. 14.
1. 1. 15. inf
在 pandas 或 numpy 中是否有一種簡單/優雅的方法?我嘗試過回圈,但它們很混亂而且效率極低,我嘗試過使用np.unique:
target_array = np.unique(initial_array[:, 0:2], axis=0)
這會產生
x y
0. 0.
0. 1.
1. 1.
這是一個好的開始,但后來我堅持生成最后兩列。
uj5u.com熱心網友回復:
IIUC,你可以使用
out = (df.groupby(['x', 'y'])['t']
.agg(t1='min', t2='max', c='count')
.reset_index()
.pipe(lambda df: df.assign(t2=df['t2'].mask(df['c'].eq(1), np.inf)) )
.drop(columns='c')
)
print(out)
x y t1 t2
0 0.0 0.0 10.0 12.0
1 0.0 1.0 13.0 14.0
2 1.0 1.0 15.0 inf
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484227.html
上一篇:多種長度系列
