0

I have a dataframe I'm reading from a file. I've also added the coordinates of each data point (they were taken at different locations) to the dataframe, with an X and Y column. These numbers are converted to floats before being added to the dataframe. To make a dataframe that includes those coordinates would be something like this:

d = {'X': [0.667, 0.667, -0.667, -0.667, 0.667, -0.667, 2, 2, -2, -2, 2, -2],
     'Y': [0.5, -0.5, 0.5, -0.5, 0, 0, 0.5, -0.5, 0.5, -0.5, 0, 0]}
df = pd.DataFrame(data=d)

I want to sort this by X value, because I'm graphing things vs X. However if I do

df.sort_values('X')

it actually doesn't sort it at all. I have ensured that these numbers are floats by putting something I found in a different Stack Overflow answer:

df.assign(X=df.X.astype(float))

before the sorting, and type(data['X'][0]) returns numpy.float64 so I know these are floats. Every other answer on this I've found, it turned out the column was actually strings. What gives? Why isn't it sorting the floats correctly?

To put all the code into a block, this should reproduce it...

import pandas as pd
d = {'X': [0.667, 0.667, -0.667, -0.667, 0.667, -0.667, 2, 2, -2, -2, 2, -2],
     'Y': [0.5, -0.5, 0.5, -0.5, 0, 0, 0.5, -0.5, 0.5, -0.5, 0, 0]}
df = pd.DataFrame(data=d)
df.assign(X=df.X.astype(float))
df.sort_values('X')
df
0

1 Answer 1

0

I feel so silly. I just had to add inplace=True to the sort_values call. Answering this and leaving it up for other people like me Googling in the future.

Sign up to request clarification or add additional context in comments.

1 Comment

@BigBen That's so weird. That didn't come up in my search results, but I was searching specifically for "sorting negative values incorrectly"...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.