pandas cut multiple columns with labels?

Viewed 543

I want to cut and label the values in multiple columns. Basically this:

df[numericColumn] = pd.cut(df[numericColumn], 3, labels=["small", "medium", "big"])

I found this code (which works) but doesn't do the labelling I want, when I replace bin with labelling it errors out and says I need to include a bin

df = pd.DataFrame(np.random.rand(10,4))
df.apply(pd.cut, bins=[0,0.5,1])

Is there a way to cut label multiple columns in pandas?

1 Answers

So pulling this apart a little to show what is going on. You will see that you can set up the bins and then do the cut row by row, then change the result of the cut back to the category names that you want to use.

# set up a dataframe
df = pd.DataFrame(np.random.rand(10,4))
df.columns = ['col1','col2','col3','col4']

# set up the intervals
bins = pd.IntervalIndex.from_tuples([(0, 0.33), (0.33, 0.66), (0.66, 1)])

# do the cut on col1 for example
x = pd.cut(df["col1"].to_list(),bins)

# change the name of the catagories
x.categories = ['small','medium','large']
# put it back
df['col1'] = x

gives

    col1    col2        col3        col4
0   large   0.589432    0.545828    0.257144
1   medium  0.625025    0.087607    0.548300
2   small   0.538186    0.057027    0.023201
3   medium  0.686324    0.027694    0.819753
4   medium  0.850623    0.977317    0.782361
5   large   0.375888    0.209709    0.903763
6   medium  0.094957    0.583052    0.534926
7   large   0.101968    0.863916    0.929300
8   large   0.612073    0.005553    0.723863
9   large   0.814393    0.327281    0.463976

and if you want to iterate through the whole dataframe

# set up a dataframe
df = pd.DataFrame(np.random.rand(10,4))
df.columns = ['col1','col2','col3','col4']

# set up the intervals
bins = pd.IntervalIndex.from_tuples([(0, 0.33), (0.33, 0.66), (0.66, 1)])
names = ['small','medium','large']

for col in df.columns:
    x = pd.cut(df[col].to_list(),bins)
    x.categories = names
    df[col] = x
Related