简体   繁体   中英

Python, how to sort dataframe by string column in ascending

I have the following dataframe 1

The campaign is stored as a string, and I want to sort by the campaign column in ascending order. I tried converting it to an integer with the following code, but it still only sorts as it does in the screenshot (1,10,2,20 instead of 1,2,10,20)

df[["campaign"]] = df[["campaign"]].apply(pd.to_numeric)
df.sort_values(by=['campaign'])

How can I fix this?

Use this to convert string values in the campaign column to numeric values:

df["campaign"] = pd.to_numeric(df["campaign"], errors='coerce')

to sort based on campaign column use:

df.sort_values("campaign", inplace=True)

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