python入门系列(14): python对字符串型数据处理

本文介绍如何使用sklearn的LabelEncoder进行类别特征编码,并通过pandas实现独热编码。详细展示了从读取Excel文件到编码的具体步骤,以及如何处理字符串类型的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. sklearn包

1.1 labelEncoder

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(df['Col1'])
df['Col3'] = le.transform(df['Col3'])

再来一个示例

###
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder

le = preprocessing.LabelEncoder()
le.fit(["paris", "paris", "tokyo", "amsterdam"])
LabelEncoder()

print(list(le.classes_))

# ['amsterdam', 'paris', 'tokyo']

print(le.transform(["tokyo", "tokyo", "paris"])) 

# array([2, 2, 1])

这里结合读取文件,来实现字符编码。

import numpy as np
import pandas as pd
import xlrd
from tqdm import tqdm

from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder

#### obtain cols of XX type
def obtain_x(train_df,xtype):
	dtype_df = train_df.dtypes.reset_index()
	print('dtype_df\n',dtype_df)
	dtype_df.columns = ['col','type']
	return dtype_df[dtype_df.type==xtype].col.values


train_df = pd.read_excel(r'G:\test_onehot.xlsx')
# print('train_df',train_df)

# obtain str cols
str_col = obtain_x(train_df,'object')#获得字符串类型列代号

print('str_col\n',str_col)

str_col_list=str_col.tolist()
print('str_list\n',str_col_list)

# print('obtained float cols, and count:',len(float64_col))

print('train_df[str_col_list]\n',train_df[str_col_list])

###编码
le = preprocessing.LabelEncoder()
# list= [col for col in str_col ]

list=[]
# list=str_col_list

# list.append(train_df[col] for col in str_col_list)
list.append(train_df[str_col_list[0]])
list.append(train_df[str_col_list[1]])
	
print('list\n',list[1][0])
le.fit(list[0])
LabelEncoder()
print('le.transform(list[0])\n',le.transform(list[0]))

2. 使用pandas包处理

2.1 独热编码

import pandas as pd

train_df = pd.read_excel(r'G:\test_onehot.xlsx')
# print('train_df',train_df)
 
#get_dummies

# obtain str cols
str_col = obtain_x(train_df,'object')#获得字符串类型列代号

train_df_dummy=pd.get_dummies(train_df[str_col])
train_df=train_df.drop(str_col,axis=1)

train_df=train_df.join(train_df_dummy)

print('train_df\n',train_df)

参考:

  1. pandas处理字符串型数据
  2. sklearn_labelEncoder;
  3. 独热编码优快云
  4. 独热编码_GitHub
  5. 独热编码的两种实现方式panda和sklearn
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rosefunR

你的赞赏是我创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值