gpt4 book ai didi

python - 如何仅对数据集的特定列进行标签编码?

转载 作者:行者123 更新时间:2023-11-28 19:00:50 24 4
gpt4 key购买 nike

假设我现在有一个这样的数据集,我只想对具有字符串值的特定列进行编码。就像下面提到的数组一样,我只想对 a[0][0]、a[0][1]、a[0][3]、a[0][4] 进行 LabelEncode。

a = [[Andaman and Nicobar Islands, NICOBARS, 2000, Kharif, Arecanut, 1254.0, 2000.0]]

我试过的是:

dataset = pd.read_csv('crop_production.csv')

from sklearn import preprocessing

le = preprocessing.LabelEncoder()
dataset = dataset.apply(le.fit_transform)

但它甚至对数值进行编码。

知道如何只对 csv 的特定列进行编码吗?

数据集示例:

State_Name  District_Name   Crop_Year   Season  Crop    Area    Production

Andaman and Nicobar Islands NICOBARS 2000 Kharif Arecanut 1254.0 2000.0

最佳答案

考虑如下所示的示例数据框

sample = pd.DataFrame()

sample['A'] = ['a', 'b', 'c', 'a']
sample['B'] = ['x', 'y', 'x', 'z']
sample['C'] = [1, 2, 3, 4]
sample['D'] = ['m', 'n', 'm', 'o']


# sample dataframe

A B C D
0 a x 1 m
1 b y 2 n
2 c x 3 m
3 a z 4 o

这里的 A、B 和 D 列包含字符串,C 列是数字。因此,您想对 A、B 和 D 进行编码,但不对 C 进行编码。为此,您可以制作一个特定于一列的编码器,并根据需要对该列进行编码。请参阅以下代码。

from sklearn.preprocessing import LabelEncoder

encoder_A = LabelEncoder()
encoder_B = LabelEncoder()
encoder_D = LabelEncoder()

sample['A'] = encoder_A.fit_transform(sample['A'])
sample['B'] = encoder_B.fit_transform(sample['B'])
sample['D'] = encoder_D.fit_transform(sample['D'])

# encoded dataframe

A B C D
0 0 0 1 0
1 1 1 2 1
2 2 0 3 0
3 0 2 4 2

您可以轻松地将此代码扩展到您的特定问题。

关于python - 如何仅对数据集的特定列进行标签编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52810643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com