方法1:
使用map()函数实现文字型数据转换数字型数据
import pandas as pd
# 创建DataFrame
df = pd.DataFrame([['AAA'], ['BBB'], ['CCC']])
# 设置对应的数字
dict1 = {'AAA':1,
'BBB':2,
'CCC':3}
# 字符转换数字
df.iloc[:,0] = df.iloc[:,0].map(dict1)
方法2:
使用sklearn实现
from sklearn.preprocessing import LabelEncoder
import pandas as pd
df = pd.DataFrame([['AAA'], ['BBB'], ['CCC']])
df = LabelEncoder().fit_transform(df.iloc[:,0])
方法3:
lambda函数实现
import pandas as pd
df = pd.DataFrame([['AAA'], ['BBB'], ['CCC']])
df1 = df[0].apply(lambda x:1 if x == 'AAA' else 2 if x == 'BBB' else 3)