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