将数据框列的值转换为数字 [英] convert dataframe columns value into digital number

查看:210
本文介绍了将数据框列的值转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框列中有以下数据.如何通过数字转换每个域名?我尝试在for循环中使用replace.但是,由于我拥有1200多个unqie域名.我不想看来这不是一个好主意

I have following data in my column of data frame. How can I convert each domain name by digital number? I try to use replace in a for loop. However, since I have more than 1200 unqie domain name. I do not want to It seems like it is not a idea way to do it

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
....

推荐答案

让我们使用 pd.factorize :

Let's use 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

这篇关于将数据框列的值转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆