你可以使用以下基本语法将pandas DataFrame中的分类变量转换为数字变量。
df['column_name'] = pd.factorize(df['column_name'])[0]
你也可以使用以下语法将DataFrame中的每个分类变量转换为数字变量。
#identify all categorical variables
cat_columns = df.select_dtypes(['object']).columns
#convert all categorical variables to numeric
df[cat_columns] = df[cat_columns].apply(lambda x: pd.factorize(x)[0])
下面的例子展示了如何在实践中使用这种语法。
例1:将一个分类变量转换为数字变量
假设我们有下面这个pandas DataFrame。
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
'position': ['G', 'G', 'F', 'G', 'F', 'C', 'G', 'F', 'C'],
'points': [5, 7, 7, 9, 12, 9, 9, 4, 13],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12, 10]})
#view DataFrame
df
team position points rebounds
0 A G 5 11
1 A G 7 8
2 A F 7 10
3 B G 9 6
4 B F 12 6
5 B C 9 5
6 C G 9 9
7 C F 4 12
8 C C 13 10
我们可以使用下面的语法将 "团队 "列转换为数字。
#convert 'team' column to numeric
df['team'] = pd.factorize(df['team'])[0]
#view updated DataFrame
df
team position points rebounds
0 0 G 5 11
1 0 G 7 8
2 0 F 7 10
3 1 G 9 6
4 1 F 12 6
5 1 C 9 5
6 2 G 9 9
7 2 F 4 12
8 2 C 13 10
下面是转换的过程。
- 每个值为'A'的球队都被转换为0。
- 每支价值为'B'的球队被转换为1。
- 每一个数值为 "C"的团队被转换为2。
例2:将多个分类变量转换为数字变量
再一次假设我们有以下pandas数据框架。
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
'position': ['G', 'G', 'F', 'G', 'F', 'C', 'G', 'F', 'C'],
'points': [5, 7, 7, 9, 12, 9, 9, 4, 13],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12, 10]})
#view DataFrame
df
team position points rebounds
0 A G 5 11
1 A G 7 8
2 A F 7 10
3 B G 9 6
4 B F 12 6
5 B C 9 5
6 C G 9 9
7 C F 4 12
8 C C 13 10
我们可以使用下面的语法将DataFrame中的每个分类变量转换为数字变量。
#get all categorical columns
cat_columns = df.select_dtypes(['object']).columns
#convert all categorical columns to numeric
df[cat_columns] = df[cat_columns].apply(lambda x: pd.factorize(x)[0])
#view updated DataFrame
df
team position points rebounds
0 0 0 5 11
1 0 0 7 8
2 0 1 7 10
3 1 0 9 6
4 1 1 12 6
5 1 2 9 5
6 2 0 9 9
7 2 1 4 12
8 2 2 13 10
注意,两个分类列(球队和位置)都被转换为数字,而得分和篮板列则保持不变。
注:你可以在这里找到pandas**factorize()**函数的完整文档。
其他资源
下面的教程解释了如何在pandas中执行其他常见操作。
如何将Pandas DataFrame列转换为字符串
如何将Pandas DataFrame列转换为整数
如何在Pandas DataFrame中将字符串转换为浮点数
The postHow to Convert Categorical Variable to Numeric in Pandasappeared first onStatology.