在 Pandas 中将数值转换为分类值
Converting Numerical Values to Categorical in Pandas
我正在尝试将特定列的所有值从数字转换为分类。
我的列目前包含 2 个值,0 和 1,我想更改它,以便 0 成为字符串值 'TypeA',1 成为字符串值 'TypeB'
我曾尝试像这样映射我的专栏,但没有奏效:
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()
目标列仍然这样显示:
test['target'].describe
<bound method NDFrame.describe of 0 1
1 1
2 1
3 1
4 0
5 1
当我想这样出现时:
<bound method NDFrame.describe of 0 1
1 TypeB
2 TypeB
3 TypeB
4 TypeA
5 TypeB
使用Series.map
:
考虑 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
如果您想在新列中查看地图,可以尝试另一种方法 -
>>> 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
我正在尝试将特定列的所有值从数字转换为分类。
我的列目前包含 2 个值,0 和 1,我想更改它,以便 0 成为字符串值 'TypeA',1 成为字符串值 'TypeB'
我曾尝试像这样映射我的专栏,但没有奏效:
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()
目标列仍然这样显示:
test['target'].describe
<bound method NDFrame.describe of 0 1
1 1
2 1
3 1
4 0
5 1
当我想这样出现时:
<bound method NDFrame.describe of 0 1
1 TypeB
2 TypeB
3 TypeB
4 TypeA
5 TypeB
使用Series.map
:
考虑 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
如果您想在新列中查看地图,可以尝试另一种方法 -
>>> 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