变量类别转换

当str数据不适合分析时

方法一:

def car1(s):
    it = {b'vhigh': 1, b'high': 2, b'med': 3, b'low': 4}
    return it[s]

path ='C:/Users/tjh/Desktop/car.data.txt'  # 之前保存的文件路径
data = np.loadtxt(path,                          # 路径
                  dtype=float,                   # 数据类型
                  delimiter=',',                 # 数据以什么分割符号分割数据
                  converters={0:car1,1:car1})     
# 对某列数据进行某种类型的转换

方法二:

path = 'C:/Users/tjh/Desktop/car.data.txt'
data = pd.read_csv(path)

data['buying']=data['vhigh'].replace(['vhigh','high','med','low'],['1','2','3','4']).astype('int')
data['maint']=data['vhigh.1'].replace(['vhigh','high','med','low'],['1','2','3','4']).astype('int')

删除列:data=data.drop('unacc',1)

猜你喜欢

转载自blog.csdn.net/qq_34363237/article/details/84064521