所以我的 str 列表是:
col = ['cat1','cat2','cat3']
我想像这样转换成 int 列表:
col = [0,1,2]
我试过:
col=pd.Series(col)
col=pd.to_numeric(col)
但它给出了错误:
无法解析位置 0 处的字符串“cat1”
最佳答案
In [4719]: pd.Series(col).astype('category').cat.codes
Out[4719]:
0 0
1 1
2 2
dtype: int8
或者,
In [4726]: pd.Series(pd.factorize(col)[0])
Out[4726]:
0 0
1 1
2 2
dtype: int64
或者,
In [4738]: np.unique(col, return_inverse=True)[1]
Out[4738]: array([0, 1, 2], dtype=int64)
或者,
In [4739]: pd.Categorical(col).codes
Out[4739]: array([0, 1, 2], dtype=int8)
如果需要作为列表,最后使用 .tolist()
。
关于python-2.7 - 将字符串列表转换为整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46843834/