python-2.7 - 将字符串列表转换为整数列表

标签 python-2.7 pandas

所以我的 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/

相关文章:

python - `__repr__` 函数对正常函数的意义是什么

python - 填充 Pandas 中其他列的邻居值的值

python - 防止 GridSpec 子图分离随图形大小而变化

python - 如何使用For循环将整数作为字符串添加到列表中?

python-2.7 - 如何合并两个数据框而不丢失任何行

python - 如何将不返回数值的函数应用于 Pandas 滚动窗口?

python - 在python中处理多个csv文件

python - 解析数据框

java - StanfordPOSTagger 不与 NLTK 一起工作

python - 在不产生 python 开销的情况下在 Cython 中定义 NumPy 数组