这段代码一直有效,直到我将python 2.x升级到3.x.
我有一个由3列ipk1,ipk2,ipk3组成的df.
ipk1,ipk2,ipk3由浮点数0 – 4.0组成,
我想将它们分成字符串.
数据看起来像这样:
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
在python 2.x上这段代码可以工作但是在我升级到python 3之后它不是.有没有其他方法将其捆绑成字符串?我尝试过使用它虽然也没有任何帮助.
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'
我收到的错误:
TypeError: '>' not supported between instances of 'str' and 'float'
我的预期产量:
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
解决方法:
这是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)