python - 从字符串中提取整数

标签 python label

我想为聚类问题创建目标列表,其中包含数据集每个实例的类名称(标签)列表中的多个类。

class_name = ['class_1','class_2','class_3','class_3','class_1','class_2',\
'class_2','class_1','class_1','class_2','class_1','class_3'] 

目标列表应该像一个与class_name列表长度相同的数组,其中一个整数被分配给不同的类标签。哪种投注方式可以得到这个?

target = np.array([1, 2, 3, 3, 1, 2, 2, 1, 1, 2, 1, 3])

类标签(例如 class_1)的格式为“Xx_xx_xxx(A123)”或“Xx_xx_xxx (A123)”。括号内的文字不固定。列表类型是'unicode'

最佳答案

您应该做的第一件事是以标准格式获取类。根据上面的描述,如果类名位于字符串的括号中,那么您可以使用正则表达式来获取类名。

import re
X = ['abc(class_1)', 'cde_(class_1)', 'def_(class_2)']
just_classes = [re.findall(r'\((.*)\)', thing)[0] for thing in X]
# ['class_1', 'class_1', 'class_2']

您可以在此处使用几种不同的方法。如果您使用 numpy、scipy 堆栈进行机器学习,我建议您学习 sklearn 库。它有很多有用的机器学习和人工智能工具,包括编码类名。

使用sklearn

from sklearn.preprocessing import LabelEncoder
class_names = ['class_1','class_2','class_3','class_3','class_1','class_2',\
        'class_2','class_1','class_1','class_2','class_1','class_3'] 

my_enc = LabelEncoder()
my_enc.fit(class_names)
encoded1 =  my_enc.transform(class_names)

没有外部库

classes = set(class_names)
d = {c:i for i,c in enumerate(classes)}
encoded2 = [d[c_name] for c_name in class_names]
print encoded1 #approach 1 gives numpy array
print encoded2 # approach 2 gives standard python list

这两种方法都应该有效。自己实现的代码并不多,但总的来说,我建议查看 sklearn preprocessing工具。

关于python - 从字符串中提取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35374323/

相关文章:

MATLAB 子图标题和轴标签

c# - 在c#中更改标签部分的颜色

c - 如果我在程序中编写一个没有 goto 语句的标签,会发生什么?

java - JUNG(Java 图): How to prevent Vertex- and Edge-Labels from overlapping?

python - python plot get_loc(self,key,method,tolerance)错误

python - 使用Python将OpenCV cv.Rectangle(img,pt1,pt2)转换为NumPy数组

python - 如何正确测量jupyter中单元格的执行时间?

python - 如何使用pyUnrar2获取解压目录?

python - 使用 glob 获取文件名

r - 使用haven导入Stata数据后访问变量标签的便捷方法