如何使数据框中的最小值低于某个阈值?
How to get minimum values in dataframe below a certain threshold?
我在 pandas 中有 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')
以获得所有事物的欧氏距离,但我正在努力 select 我需要的值(即距离 < 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
中满足条件distance < 5
的(i,j)对。
- 我们使用上一步获得的索引构建了一个新的数据框。
idx[0]
给出了df1
中我们需要获取的部分,idx[1]
给出了df2
中我们需要获取的部分。
我在 pandas 中有 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')
以获得所有事物的欧氏距离,但我正在努力 select 我需要的值(即距离 < 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
中满足条件distance < 5
的(i,j)对。 - 我们使用上一步获得的索引构建了一个新的数据框。
idx[0]
给出了df1
中我们需要获取的部分,idx[1]
给出了df2
中我们需要获取的部分。