作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我现在有一个这样的数据集,我只想对具有字符串值的特定列进行编码。就像下面提到的数组一样,我只想对 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/
我是一名优秀的程序员,十分优秀!