简体   繁体   English

在 Pandas 中将数值转换为分类

[英]Converting Numerical Values to Categorical in Pandas

I am attempting to convert all my values for a certain column from numerical to categorical.我正在尝试将某个列的所有值从数字转换为分类。

My column currently holds 2 values, 0 and 1 and i would like to change it so that 0 becomes a string value 'TypeA' and 1 becomes a string value 'TypeB'我的列当前包含 2 个值,0 和 1,我想更改它,使 0 变为字符串值“TypeA”,1 变为字符串值“TypeB”

I have attempted to map my my columns like this but it has not worked:我曾尝试像这样对我的专栏进行 map,但它没有奏效:

test['target'] = test['target'].map(str)
type_mapping2 = {0 : 'TypeA', 1 : 'TypeB'}
test = test.applymap(lambda s: type_mapping2.get(s) if s in type_mapping else s)
test.head()

The target column still appears like this:目标列仍然如下所示:

test['target'].describe
<bound method NDFrame.describe of 0       1
1       1
2       1
3       1
4       0
5       1

When I would like to appear like this:当我想像这样出现时:

<bound method NDFrame.describe of 0       1
1       TypeB
2       TypeB    
3       TypeB
4       TypeA
5       TypeB

Use Series.map :使用Series.map

Consider df :考虑df

In [532]: df
Out[532]: 
   col
0    1
1    1
2    1
3    0
4    1

In [533]: type_mapping2 = {0 : 'TypeA', 1 : 'TypeB'}

In [535]: df['col'] = df['col'].map(type_mapping2)

In [536]: df
Out[536]: 
     col
0  TypeB
1  TypeB
2  TypeB
3  TypeA
4  TypeB

If you would like to see the map in a new column, here is another method to try -如果您想在新专栏中看到 map,这里是另一种尝试的方法 -

>>> df
   col
0    1
1    1
2    1
3    0
4    1
>>> type_map = {0: 'TypeA', 1: 'TypeB'}
>>> df['type_map'] = df['col'].map(type_map) # new col to be named 'type_map'
>>> df
   col type_map
0    1    TypeB
1    1    TypeB
2    1    TypeB
3    0    TypeA
4    1    TypeB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM