2017-08-27 62 views
1

我在数据框的列中有以下数据。如何通过数字号码转换每个域名?我尝试在for循环中使用replace。但是,因为我有超过1200个unqie域名。我不想现在看来似乎不是一个主意办法做到这一点将数据帧列值转换为数字编号

for i, v in np.ndenumerate(np.unique(df['domain'])): 
    df['domain'] = df['domain'].replace(to_replace=[v], value=i[0]+1, inplace=True) 

,但它不工作

data frame: 
    type domain 
0 1  yahoo.com 
1 1  google.com 
2 0  google.com 
3 0  aa.com 
4 0  google.com 
5 0  aa.com 
6 1  abc.com 
7 1  msn.com 
8 1  abc.com 
9 1  abc.com 
.... 

我要转换为

type domain 
0 1  1 
1 1  2 
2 0  2 
3 0  3 
4 0  2 
5 0  3 
6 1  4 
7 1  5 
8 1  4 
9 1  4 
.... 

回答

5

让我们使用pd.factorize

df.assign(domain=pd.factorize(df.domain)[0]+1) 

输出:

type domain 
0  1  1 
1  1  2 
2  0  2 
3  0  3 
4  0  2 
5  0  3 
6  1  4 
7  1  5 
8  1  4 
9  1  4 
+2

尼斯一个:-)〜+1 – Wen

1

如果对于数字号码分配真的很重要,你可以试试这个

import pandas as pd 

df.domain.astype('category').cat.codes 

Out[154]: 
0 4 
1 2 
2 2 
3 0 
4 2 
5 0 
6 1 
7 3 
8 1 
9 1 
dtype: int8 

如果是这样的事情,你可以尝试

maplist=df[['domain']].drop_duplicates(keep='first').reset_index(drop=True).reset_index().set_index('domain') 
maplist['index']=maplist['index']+1 
df.domain=df.domain.map(maplist['index']) 
    Out[177]: 
    type domain 
0  1  1 
1  1  2 
2  0  2 
3  0  3 
4  0  2 
5  0  3 
6  1  4 
7  1  5 
8  1  4 
9  1  4