4

I want to sort a pandas dataframe based on a column, but the values are stored as strings, but they should be treated as integers.

df.sort(col1)

where col1 = ['0','1','12','13','3'].

How can I use it so that it considers these numbers as integers and not strings?

2 Answers 2

3

If you want to keep your dataframe untouched and just want to sort it...
This is assuming col1 is a column in your dataframe df

option 1

df.iloc[df['col1'].astype(int).argsort()]

option 2
You can also use pd.to_numeric

df.iloc[pd.to_numeric(df['col1']).argsort()]

option 3
For more efficiency you can reconstruct manipulating the underlying numpy array

v = df.values
a = df['col1'].values.astype(int).argsort()
pd.DataFrame(v[a], df.index[a], df.columns)

See also

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

Comments

2

You can try this before sorting:

df['col1'] = df['col1'].astype(int)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.