![](/img/trans.png)
[英]Replace values in a dataframe column that are below a certain threshold with NaN
[英]How to get minimum values in dataframe below a certain threshold?
我在熊猫中有2个数据框,其中包含汽车和树木的位置信息。
DF1
x y
car
3 216 13
4 218 12
5 217 12
DF2
x y
tree
5 253 180
6 241 24
8 217 14
我将如何计算每辆汽车与每棵树之间的欧几里得距离,然后过滤出小于例如5的距离? 我想用车号和树号以及两者之间的距离创建另一个数据框(请参见下文)
DF3
car tree dist
5 8 2.2
到目前为止,我可以使用
distance = scipy.spatial.distance.cdist(df1, df2, metric='euclidean')
以获得所有物体的欧几里得距离,但是我在努力选择所需的值(即距离<5)。 帮助表示赞赏,谢谢!!
这是一种方法:
import pandas as pd
from toolz import concat
import scipy
df1 = pd.DataFrame([[3, 216, 13],
[4, 218, 12],
[5, 217, 12]],
columns=['car', 'x', 'y'])
df1 = df1.set_index('car')
df2 = pd.DataFrame([[5, 253, 180],
[6, 241, 24],
[8, 217, 14]],
columns=['tree', 'x', 'y'])
df2 = df2.set_index('tree')
indices = list(map(list, zip(*[(x, y) for x in df1.index for y in df2.index])))
distance = scipy.spatial.distance.cdist(df1, df2, metric='euclidean')
df3 = pd.DataFrame({'car': indices[0], 'tree': indices[1], 'distance': list(concat(distance))})
df4 = df3[df3['distance'] < 5]
distance = spatial.distance.cdist(df1, df2, metric='euclidean')
idx = np.where(distance < 5)
pd.DataFrame({"car":df1.iloc[idx[0]].index.values,
"tree":df2.iloc[idx[1]].index.values,
"dist": distance[idx]})
car dist tree
0 3 1.414214 8
1 4 2.236068 8
2 5 2.000000 8
cdist
的(i,j)项是第一组项目中的第i个项目与第二组项目中的第j个项目之间的距离。 np.where
来标识满足条件distance < 5
distance
中的(i,j)对。 idx[0]
给出了我们需要检索的df1
的部分,而idx[1]
给出了我们需要获取的df2
中的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.