user248237
user248237

Reputation:

sorting pandas dataframes according to cut in python?

if I use pandas.cut to generate bins labels like [0.3, 0.5), ..., how can I sort the dataframe according to these bins in ascending order? E.g. [-0.4, -0.2) should come before [-0.2, 0.0), etc. Example:

df = pandas.DataFrame({"a": np.random.randn(10)})
# bin according to cut
df["bins"] = pandas.cut(df.a, np.linspace(-2,2,6))

Now how can you sort df according to the labels generated by cut (the df["bins"] column)?

Upvotes: 4

Views: 4146

Answers (2)

EdChum
EdChum

Reputation: 394159

If you sort df by column 'a' first then you don't need to sort the 'bins' column

import pandas as pd
import numpy as np
df = pd.DataFrame({"a": np.random.randn(10)})
# for versions older than 0.17.0
df.sort(by=['a'],inplace=True)
# if running a newer version 0.17.0 or newer then you need
df.sort_values(by=['a'],inplace=True)
# bin according to cut
df["bins"] = pd.cut(df.a, np.linspace(-2,2,6))
df

Out[37]:
          a          bins
6 -1.273335    (-2, -1.2]
7 -0.604780  (-1.2, -0.4]
1 -0.467994  (-1.2, -0.4]
8  0.028114   (-0.4, 0.4]
9  0.032250   (-0.4, 0.4]
3  0.138368   (-0.4, 0.4]
0  0.541577    (0.4, 1.2]
5  0.838290    (0.4, 1.2]
2  1.171387    (0.4, 1.2]
4  1.770752      (1.2, 2]

Upvotes: 8

avs
avs

Reputation: 65

Since pandas .17, the new way to sort is to use sort_values. The preferred solutions becomes:

import pandas as pd
import numpy as np
df = pd.DataFrame({"a": np.random.randn(10)})
df.sort_values('a',inplace=True)
# bin according to cut
df["bins"] = pd.cut(df.a, np.linspace(-2,2,6))
df

Upvotes: 1

Related Questions