【发布时间】:2018-07-05 22:00:49
【问题描述】:
我有一个像这样的 pandas 数据框,我尝试按“dist”列排序。排序后的数据框应以 E 或 F 开头,如下所示。我使用它不适合我的 sort_values。该函数正在计算从“开始”位置到位置列表 ['C', 'B', 'D', 'E', 'A', 'F'] 的距离,然后应该按升序对数据帧进行排序使用“dist”列排序。 有人可以告诉我为什么排序不起作用吗?
locations = {'Start':(20,5),'A':(10,3), 'B':(5,3), 'C':(5, 7), 'D':(10,7),'E':(14,4),'F':(14,6)}
loc_list
Out[194]: ['C', 'B', 'D', 'E', 'A', 'F']
def closest_locations(from_loc_point, to_loc_list):
lresults=list()
for list_index in range(len(to_loc_list)):
dist= hypot(locations[from_loc_point[0]][0] -locations[to_loc_list[list_index]][0],locations[from_loc_point[0]][1] -locations[to_loc_list[list_index]][1]) # cumsum distante
lista_dist = [from_loc_point[0],to_loc_list[list_index],dist]
lresults.append(lista_dist[:])
RESULTS = pd.DataFrame(np.array(lresults))
RESULTS.columns = ['from','to','dist']
RESULTS.sort_values(['dist'],ascending=[True],inplace=True)
RESULTS.index = range(len(RESULTS))
return RESULTS
closest_locations(['Start'], loc_list)
Out[189]:
from to dist
0 Start D 10.19803902718557
1 Start A 10.19803902718557
2 Start C 15.132745950421555
3 Start B 15.132745950421555
4 Start E 6.08276253029822
5 Start F 6.08276253029822
closest_two_loc.dtypes 出[247]:
from object
to object
dist object
dtype: object
【问题讨论】:
-
什么是
hypot函数? -
我使用hypot来计算两点之间的距离,使用它们的坐标。这部分工作正常,我获得了我已经发布的距离表。我的问题是我无法对其进行排序。 docs.python.org/2/library/math.html (math.hypot(x, y) 返回欧几里得范数,sqrt(xx + yy)。这是向量从原点到点 (x, y) 的长度.)
-
我能看到的唯一解释正在发生的事情的选项是 dist 列中的条目是字符串而不是浮点数。你能检查 type(Results["dist"].iloc[0]) 返回一个字符串还是一个浮点数吗?
标签: python pandas sorting dataframe