测试和训练数据有不同的城市,如何查找差异并在测试和训练数据的两列上使用相同的编码系统进行编码

问题描述 投票:0回答:2

我有一个测试集和训练集。他们有一个城市列,其中一个(火车)有 290 个唯一的,测试有 30 个。我希望有重叠,即伦敦、布里斯托尔都在两组中,但格洛斯特可能在一组上,而不是另一组上。

我还想将这些城市编码为两个集合之间相关的数值,因此伦敦应该在测试和训练中编码为 1。

我查看了 LabelEncoder,但不知道如何让两个集合对它们共享的城市使用相同的编号。

LabelEncoder 工作正常,但两组之间没有相关性。

之前:

df_train['City']
'London' , 'Bristol', 'Paris', 'Rome', 'London', 'Worcester'

df_test['City']
'Paris', 'Rome','Rome','London', 'Gloucester'

输出:

df_train['City']
1 2 3 4 1 6

df_test['City']
3 4 4 1 7
pandas machine-learning encoding linear-regression categorical-data
2个回答
1
投票

您可以使用常见的

CategoricalDtype

df_train = pd.DataFrame({'City': ['London' , 'Bristol', 'Paris', 'Rome', 'London', 'Worcester']})
df_test = pd.DataFrame({'City': ['Paris', 'Rome','Rome','London', 'Gloucester']})

cat = pd.CategoricalDtype(pd.concat([df_train['City'], df_test['City']]).unique())

df_train['code'] = df_train['City'].astype(cat).cat.codes
df_test['code'] = df_test['City'].astype(cat).cat.codes

输出:

# df_train
        City  code
0     London     0
1    Bristol     1
2      Paris     2
3       Rome     3
4     London     0
5  Worcester     4

# df_test
         City  code
0       Paris     2
1        Rome     3
2        Rome     3
3      London     0
4  Gloucester     5

或者只是将城市转换为分类:

df_train['City'] = df_train['City'].astype(cat)
df_test['City'] = df_test['City'].astype(cat)

0
投票

我遇到了同样的问题,我选择使用映射。

city_mapping = {'Kampala': 0, 'Nairobi': 1,
                'Lagos': 2, 'Bujumbura':3,
               'Kisumu':4, 'Gulu':5,
                'Accra':6, 'Yaoundé':7
} 
country_mapping = {
    'Uganda':0, 'Burundi':1, 
    'Kenya':2, 'Nigeria':3,
    'Cameroon':4, 'Ghana':5
}

#Encoding the city variable 
train_df['city'] = train_df['city'].replace(city_mapping)
test_df['city'] = test_df['city'].replace(city_mapping)

#Encoding the country variable
train_df['country'] = train_df['country'].replace(country_mapping)
test_df['country'] = test_df['country'].replace(country_mapping)
© www.soinside.com 2019 - 2024. All rights reserved.