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'
I have attempted to map my my columns like this but it has not worked:
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
:
Consider 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 -
>>> 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.