How to bin column of floats with pandas

前端 未结 2 902
[愿得一人]
[愿得一人] 2020-12-11 22:38

This code was working until I upgrade my python 2.x to 3.x. I have a df consisting of 3 columns ipk1, ipk2, ipk3. ipk1, ipk2, ipk3 consisting of float numbers 0 - 4.0, I wou

相关标签:
2条回答
  • 2020-12-11 23:21

    This is a good use case for pandas.cut:

    bins = [-np.inf, 1.2, 1.6, 2.0, 2.4, 2.8, 3.2, 3.6, np.inf]
    labels = ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
    
    df['ipk1'] = pd.cut(df['ipk1'], bins=bins, labels=labels)
    
    0 讨论(0)
  • 2020-12-11 23:32

    You can do this in a much simpler way using pd.cut. Here's how you could do it:

    bins = [float('-inf'),1.2,1.6,2.,2.4,2.8,3.2,3.6,float('inf')]
    labels = ['H','G','F','E','D','C','B','A']
    
    df['ipk1'] = pd.cut(df.ipk1, bins=bins, labels=labels)
    
    print(df)
    
       ipk1  ipk2  ipk3  ipk4  ipk5 jk
    0    B  3.31  3.31  3.31  3.34  P
    1    B  3.33  3.36  3.33  3.41  P
    2    B  3.47  3.59  3.55  3.60  P
    3    B  3.10  3.05  2.98  2.97  L
    4    B  3.40  3.22  3.23  3.25  L
    
    0 讨论(0)
提交回复
热议问题