How to bin column of floats with pandas

时光毁灭记忆、已成空白 提交于 2019-11-27 07:21:01

问题


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 would like to bin them into string.

The data looks something like this:

    ipk1    ipk2    ipk3    ipk4    ipk5    jk
0   3.25    3.31    3.31    3.31    3.34    P
1   3.37    3.33    3.36    3.33    3.41    P
2   3.41    3.47    3.59    3.55    3.60    P
3   3.23    3.10    3.05    2.98    2.97    L
4   3.24    3.40    3.22    3.23    3.25    L

on python 2.x this code works but after I upgrade it into python 3 it isn't. Is there any other way to bin it into string ? I have tried using while it also not help anything.

train1.loc[train1['ipk1'] > 3.6, 'ipk1'] = 'A',
train1.loc[(train1['ipk1']>3.2) & (train1['ipk1']<=3.6),'ipk1']='B',
train1.loc[(train1['ipk1']>2.8) & (train1['ipk1']<=3.2),'ipk1']='C',
train1.loc[(train1['ipk1']>2.4) & (train1['ipk1']<=2.8),'ipk1']='D',
train1.loc[(train1['ipk1']>2.0) & (train1['ipk1']<=2.4),'ipk1']='E',
train1.loc[(train1['ipk1']>1.6) & (train1['ipk1']<=2.0),'ipk1']='F',
train1.loc[(train1['ipk1']>1.2) & (train1['ipk1']<=1.6),'ipk1']='G',
train1.loc[train1['ipk1'] <= 1.2, 'ipk1'] = 'H' 

The error I receive:

TypeError: '>' not supported between instances of 'str' and 'float'

My expected output:

    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

回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/56296518/how-to-bin-column-of-floats-with-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!