gpt4 book ai didi

python - 我需要获取数据帧最密集点的坐标(x,y)

转载 作者:行者123 更新时间:2023-11-30 09:04:15 24 4
gpt4 key购买 nike

我有一个带有坐标(X,Y)的数据框,我需要获取一个包含最高密度点坐标的列表。

我使用坐标(X,Y)的平均值并计算从该点到所有其他点的距离,然后对它们进行排序,但平均值并不总是在最密集的点。使用 gaussian_kde 我可以可视化最密集的点,但我不知道如何将点提取到列表中。

import numpy as np
import pandas as pd
import pylab as plt
import random
from scipy.stats import gaussian_kde
from scipy.spatial.distance import cdist
from scipy.spatial import distance

def closest_point(point, points):
""" Find the nearest point. """
return points[cdist([point], points).argmin()]

x = [random.randint(0, 100) for x in range(1, 51)]
y = [random.randint(0, 100) for x in range(1, 51)]
fr = pd.DataFrame({'x':x,'y':y})

mx = fr['x'].mean()
my = fr['y'].mean()
fr2 = pd.DataFrame({'x':[mx],'y':[my]})

fr['Punto'] = [(x, y) for x,y in zip(fr['x'], fr['y'])]
fr2['Punto'] = [(x, y) for x,y in zip(fr2['x'], fr2['y'])]
fr2['Cercano'] = [closest_point(x, list(fr['Punto'])) for x in fr2['Punto']]

lista = fr['Punto'].tolist()
media = fr2['Punto'].tolist()

distancia_numpy = distance.cdist(lista,media, 'euclidean')
distancia_lista = np.array(distancia_numpy).tolist()
distancia_serie = pd.Series(distancia_lista)
"""
we place a new column with the distance from the average point to the nearest point
"""
fr['Distancia'] = distancia_serie
ordenado = fr.sort_values('Distancia', ascending = True)

xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
fig, ax = plt.subplots()
ax.scatter(x, y, s=50, c=z, edgecolor='')
"""in red the mean of the points"""
ax.scatter(mx, my, s=100,c='red', edgecolor='')

plt.show()
print (ordenado)

结果应该是一个列表或一个有序的数据帧,首先具有最密集的点,事实上我得到了这些结果,但它们不正确,因为平均点不位于最大密度的点。非常欢迎任何帮助

最佳答案

非常感谢!这段代码完成了工作!

point_gaus = pd.DataFrame({'x':x,'y':y,'gauss':list(z)})
point_gaus_order = point_gaus.sort_values('gauss', ascending = False)
point_gaus_order_10 = point_gaus_order[:10]
ax.scatter(point_gaus_order_10['x'],point_gaus_order_10['y'], s=25,c='red', edgecolor='')

关于python - 我需要获取数据帧最密集点的坐标(x,y),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56526858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com