python - 用数字替换字符串 numpy 数组

标签 python pandas numpy

我有一个 numpy 数组

z = array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa','Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor','Iris-virginica', 'Iris-virginica', 'Iris-virginica'])

我要替换

Iris-setosa -0
Iris-versicolor - 1
Iris-virginica - 2

应用逻辑回归。

最终输出应该是这样的

z = [ 0, 0 ,.. 1,1,.. 2,2,..]

有没有一种简单的方法来执行此操作,而不是遍历数组并使用替换命令?

最佳答案

使用factorize :

a = pd.factorize(z)[0].tolist()
print (a)
[0, 0, 0, 0, 1, 1, 1, 2, 2, 2]

numpy.unique :

a = np.unique(z, return_inverse=True)[1].tolist()
print (a)
[0, 0, 0, 0, 1, 1, 1, 2, 2, 2]

关于python - 用数字替换字符串 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48852930/

相关文章:

python - series.unique 与集合列表 - 性能

python - 如何解决类型错误: 'numpy.ndarray' object is not callable on Python

Python 3.7 及以上版本 : how to determine Linux distribution?

python - 使用具有 > 2 个参数的用户定义函数的 matplotlib 绘制 3d 曲面

python - 如何将具有 `.1` 的重复列合并到没有 `.1` 的单列中?

python - groupby后如何替换异常值?

Python 破折号 : Return subset of a data frame using drop-down menu

python - 如何存储一系列时间序列数据,包括元数据

python - Numpy savetxt 类型错误

jquery - 如何从 Django(Python) 接收 jQuery 列表