正如 Jon 所说,您可以使用 Series.factorize。
(s.factorize()[0]+1).astype('float')
要在整个 DataFrame 上按列执行此操作,只需使用 apply。
演示
>>> s = pd.Series(['Exhaust', 'Fault', 'Probation', 5, int,
'Exhaust', int, 'Fault', 'Motor'])
>>> s
0 Exhaust
1 Fault
2 Probation
3 5
4 <class 'int'>
5 Exhaust
6 <class 'int'>
7 Fault
8 Motor
dtype: object
>>> (s.factorize()[0]+1).astype('float')
array([ 1., 2., 3., 4., 5., 1., 5., 2., 6.])
一个 NumPy 解决方案可能是使用 np.unique 的 return_inverse 关键字 arg,
(np.unique(s, return_inverse=True)[1]+1).astype('float')
但是,从一些粗略的基准测试来看,Pandas 解决方案可能会更快。