Python 获取行的最小值并存储相应的索引
我有一个存储为熊猫数据帧Python 获取行的最小值并存储相应的索引,python,pandas,Python,Pandas,我有一个存储为熊猫数据帧df的距离矩阵,其中包含400对坐标之间的距离,单位为公里,如下所示: 0 1 2 3 4 .... 0 0.000000 1.740838 2.496827 2.577736 1.698938 1 1.740838 0.000000 1.373490 1.741935 1.261969 2 2.496827
df
的距离矩阵,其中包含400对坐标之间的距离,单位为公里,如下所示:
0 1 2 3 4 ....
0 0.000000 1.740838 2.496827 2.577736 1.698938
1 1.740838 0.000000 1.373490 1.741935 1.261969
2 2.496827 1.373490 0.000000 0.420828 0.812797
3 2.577736 1.741935 0.420828 0.000000 1.131974
4 1.698938 1.261969 0.812797 1.131974 0.000000
.
.
.
我感兴趣的是每个点的下一个最近坐标有多近,我得到的是:
df[df>0]。最小值(轴=1)
这表示到下一个最近点的距离,单位为KM。我还想存储下一个最近点的索引,以便:
nearest_dist nearest_id
0 0.074083 3
1 0.004708 151
2 0.119431 7
3 0.167242 4
4 0.018095 81
stack
然后groupby
+idxmin
对序列进行切片
s = df.rename_axis(columns='nearest_id').stack().loc[lambda x: x > 0]
s = (s.loc[s.groupby(level=0).idxmin()]
.to_frame('nearest_dist')
.reset_index(-1))
还可以从numpy构建数据帧
arr = df.where(df > 0).to_numpy()
pd.DataFrame({'nearest_id': np.nanargmin(arr, 1),
'nearest_dist': np.nanmin(arr, 1)},
index=df.index)
stack
然后groupby
+idxmin
对序列进行切片
s = df.rename_axis(columns='nearest_id').stack().loc[lambda x: x > 0]
s = (s.loc[s.groupby(level=0).idxmin()]
.to_frame('nearest_dist')
.reset_index(-1))
还可以从numpy构建数据帧
arr = df.where(df > 0).to_numpy()
pd.DataFrame({'nearest_id': np.nanargmin(arr, 1),
'nearest_dist': np.nanmin(arr, 1)},
index=df.index)
您可以使用
concat
和您在min
中使用的相同想法,但在idxmin
中使用
m = df>0
res = pd.concat([df[m].min(axis=1), df[m].idxmin(axis=1)],
axis=1, keys=['nearest_dist','nearest_id'])
print(res)
nearest_dist nearest_id
0 1.698938 4
1 1.261969 4
2 0.420828 3
3 0.420828 2
4 0.812797 2
或者更简单地使用agg
res = (df[m].agg(['min', 'idxmin'], axis=1)
.rename(columns={'min':'nearest_dist', 'idxmin':'nearest_id'}))
您可以使用
concat
和您在min
中使用的相同想法,但在idxmin
中使用
m = df>0
res = pd.concat([df[m].min(axis=1), df[m].idxmin(axis=1)],
axis=1, keys=['nearest_dist','nearest_id'])
print(res)
nearest_dist nearest_id
0 1.698938 4
1 1.261969 4
2 0.420828 3
3 0.420828 2
4 0.812797 2
或者更简单地使用agg
res = (df[m].agg(['min', 'idxmin'], axis=1)
.rename(columns={'min':'nearest_dist', 'idxmin':'nearest_id'}))
非常感谢。后一个简化版非常好用。谢谢!后一个简化版本非常好用。谢谢你-这个也很好用。谢谢你-这个也很好用。