Q:

Using bins in pandas data frame

I am working on a data frame which has 4 columns in total, i want to bin each column of that data frame iteratively in 8 equal parts. The bin number should be assigned to the data in a separate column for each column.
The code should work even if any different data frame is provided with different column names.
Here, is the code i tried.
for c in df3.columns:
    df3['bucket_' + c] = (df3.max() - df3.min()) // 2 + 1
    buckets = pd.cut(df3['bucket_' + c], 8, labels=False) 

sample data frame
expected output
The respected bin columns display the bin number assigned to each data point according to the range in which they will (using pd.cut to cut column in 8 equal parts) fall.
Thanks in advance!!
sample data
gp1_min gp2 gp3 gp4

17.39   23.19   28.99   44.93

0.74    1.12    3.35    39.78

12.63   13.16   13.68   15.26

72.76   73.92   75.42   94.35

77.09   84.14   74.89   89.87

73.24   75.72   77.28   92.3

78.63   84.35   64.89   89.31

65.59   65.95   66.49   92.43

76.79   83.93   75.89   89.73

57.78   57.78   2.22    71.11

99.9    99.1    100      100

100     100    40.963855    100

expected output
gp1_min gp2 gp3 gp4 bin_gp1 bin_gp2 bin_gp3 bin_gp4

17.39   23.19   28.99   44.93   2   2   2   3

0.74    1.12    3.35    39.78   1   1   1   3

12.63   13.16   13.68   15.26   1   2   2   2

72.76   73.92   75.42   94.35   5   6   6   7

77.09   84.14   74.89   89.87   6   7   6   7

73.24   75.72   77.28   92.3    6   6   6   7

78.63   84.35   64.89   89.31   6   7   5   7

65.59   65.95   66.49   92.43   5   6   5   7

76.79   83.93   75.89   89.73   6   7   6   7

57.78   57.78   2.22    71.11   4   4   1   6

99.9    99.1    100      100    8   8   8   8

100      100    40.96    100    8   8   3   8

A:

I would use a couple of functions from numpy, namely np.linspace to make the bin boundaries and np.digitize to put the dataframe's values into bins:
import numpy as np
def binner(df,num_bins):
    for c in df.columns:
        cbins = np.linspace(min(df[c]),max(df[c]),num_bins+1)
        df[c + '_binned'] = np.digitize(df[c],cbins)
    return df

