Skip to main content
 首页 » 编程设计

python之在 Pandas 中编码字符串特征

2025年05月04日23虾米哥

我有如下数据框

train_df 
'type', 'manufacturer', 'year', 'num_doors' 
sedan, bmw, 2012, 4 
couple, audi, 2014, 2 
and so on 

和test_df格式相似 所有特征都是分类特征(一些字符串,一些 int),我想将它们编码为分类变量。

在 pandas/sklearn 中处理这些分类变量的好方法是什么 此外,一旦在火车 df 上应用了转换。我还想根据这些编码对 test_df 进行编码吗?

请您参考如下方法:

读取数据时,将 dtype 指定为 category 以使每一列本质上都是分类的。

df = pd.read_csv('file.csv', dtype='category') 
df 
 
     type manufacturer  year num_doors 
0   sedan          bmw  2012         4 
1  couple         audi  2014         2 

df.dtypes 
 
type            category 
manufacturer    category 
year            category 
num_doors       category 
dtype: object 

如果您只想转换列的特定子集,可以这样做 -

f = dict.fromkeys(['type', 'manufacturer', ...], 'categorical') 

将 f 传递给 dtype。

df = pd.read_csv('file.csv', dtype=f)