Python Forum
Inconsistent sorting with the .sort_values() function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Inconsistent sorting with the .sort_values() function
#5
I would do the conversion when reading the csv file.
import pandas as pd
import io

data = io.StringIO(
    """
Name, Percent
A ,5%
B, 100%
C, 20%
D ,3%
"""
)

def percent_to_float(valuestr):
    """Convert percent to floats.  Strip trailing %, convert to float and divide by 100"""
    return float(valuestr.replace("%", "")) / 100.0

df = pd.read_csv(data, converters={"Name": str.strip, "Percent": percent_to_float})
print(df.sort_values(by=["Percent"]))
Output:
Name Percent 3 D 0.03 0 A 0.05 2 C 0.20 1 B 1.00
Reply


Messages In This Thread
RE: Inconsistent sorting with the .sort_values() function - by deanhystad - Jun-28-2022, 06:12 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: Found input variables with inconsistent numbers of samples: [5, 6] bongielondy 6 26,177 Jun-28-2021, 05:23 AM
Last Post: ricslato
  ValueError: Found input variables with inconsistent numbers of sample robert2joe 0 4,295 Mar-25-2020, 11:10 AM
Last Post: robert2joe
  ValueError: Found input variables with inconsistent numbers of samples: [0, 3] ayaz786amd 2 9,637 Nov-27-2018, 07:12 AM
Last Post: ayaz786amd

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020