[英]Converting Numerical Values to Categorical in Pandas
我正在嘗試將某個列的所有值從數字轉換為分類。
我的列當前包含 2 個值,0 和 1,我想更改它,使 0 變為字符串值“TypeA”,1 變為字符串值“TypeB”
我曾嘗試像這樣對我的專欄進行 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()
目標列仍然如下所示:
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
如果您想在新專欄中看到 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.