Ivan
Ivan

Reputation: 7746

Sorting in Pandas

I have a dataframe that contains several columns, including a column that constains "C" or "P", and another column that contains a double.

I want to first sort so that all the "C" are together, then without messing that sorting, sort by the doubles. So for example:

"C", 10.05
"P", 11.00
"P", 10.15
"C", 10.20
"C", 10.30
"P", 9.50

Should get sorted as

"C", 10.05
"C", 10.20
"C", 10.30
"P", 9.50
"P", 10.15
"P", 11.0

When I use

df.sortlevel(["c_or_p_column", "value_column"], sort_remaining=False)

I get the wrong, e.g.,

"P", 9.50
"C", 10.05
"P", 10.15
"C", 10.20
"C", 10.30
"P", 11.00

Upvotes: 0

Views: 77

Answers (1)

bnj
bnj

Reputation: 51

df = pd.DataFrame([["C", 10.05],
    ["P", 11.00],
    ["P", 10.15],
    ["C", 10.20],
    ["C", 10.30],
    ["P", 9.50]], 
    columns=['c_or_p_column', 'value_column']
)

df.sort_values(['c_or_p_column', 'value_column'], ascending=True)

Upvotes: 1

Related Questions