【问题标题】:pandas data frame sort熊猫数据框排序
【发布时间】: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


【解决方案1】:

这是你想要的吗?

locations = {'Start':(20,5),'A':(10,3), 'B':(5,3), 'C':(5, 7), 'D':(10,7),'E':(14,4),'F':(14,6)}
df= pd.DataFrame.from_dict(locations, orient='index').rename(columns={0:'x', 1:'y'})
df['dist'] = df.apply(lambda row: pd.np.sqrt((row['x'] - df.loc['Start', 'x'])**2 + (row['y'] - df.loc['Start', 'y'])**2), axis=1)
df.drop(['Start']).sort_values(by='dist')
    x  y       dist
E  14  4   6.082763
F  14  6   6.082763
A  10  3  10.198039
D  10  7  10.198039
C   5  7  15.132746
B   5  3  15.132746

或者如果你想把它包装在一个函数中

def dist_from(df, col):
    df['dist'] = df.apply(lambda row: pd.np.sqrt((row['x'] - df.loc[col,'x'])**2 + (row['y'] - df.loc[col, 'y'])**2), axis=1)
    df['form'] = col
    df.drop([col]).sort_values(by='dist')
    df.index.name = 'to'
    return df.reset_index().loc[:, ['from', 'to', 'dist']]

【讨论】:

  • 不确定。我已经有了结果数据框:'closest_locations'。我的问题是为什么排序不像描述的那样工作? most_two_loc.sort_values(by='dist',ascending=True,inplace=True)
  • 打印出数据框的 dtypes。有时值可能不是浮点数 >>df.dtypes 并发布结果
  • closest_two_loc.dtypes Out[247]: from object to object dist object dtype: object
【解决方案2】:

您需要将“dist”列中的值转换为浮点数:

df = closest_locations(['Start'], loc_list)
df.dist = list(map(lambda x: float(x), df.dist)) # convert each value to float
print(df.sort_values('dist'))                    # now it will sort properly

输出:

    from to       dist
4  Start  E   6.082763
5  Start  F   6.082763
0  Start  D  10.198039
1  Start  A  10.198039
2  Start  C  15.132746
3  Start  B  15.132746

编辑:正如@jezrael 在 cmets 中提到的,以下是一种更直接的方法:

df.dist = df.dist.astype(float)

【讨论】:

  • 很好,只有更好的是使用df.dist = df.dist.astype(float)
  • 感谢您指出 dtype 问题。我解决了在我的函数中添加这一行的问题:RESULTS['dist']= RESULTS['dist'].apply(pd.to_numeric)
  • 在这种情况下,您应该支持/接受这个答案(stackoverflow.com/help/someone-answers)。
猜你喜欢
  • 2021-10-21
  • 2017-05-16
  • 2013-10-12
  • 2021-10-14
  • 2021-05-31
  • 2019-07-05
  • 2012-12-14
  • 1970-01-01
  • 2022-11-18
相关资源
最近更新 更多