简体   繁体   中英

pandas data frame sort

I have a pandas dataframe like this which I try to sort by column 'dist'. The sorted dataframe should start with E or F as per below. I use sort_values which it is not working for me. The function is computing distances from 'Start' location to a list of locations ['C', 'B', 'D', 'E', 'A', 'F'] and then is supposed to sort the dataframe in ascending order using 'dist' column. Could someone advice me why sorting is not working?

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 Out[247]:

from    object
to      object
dist    object
dtype: object

Is this what you want?

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

or if you want to wrap it in a function

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']]

You need to convert values in "dist" column to float:

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

Output:

    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

Edit: As mentioned by @jezrael in comments, following is a more direct method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM