将pandas系列从字符串转换为唯一的int id [英] Convert pandas series from string to unique int ids

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

问题描述

我在系列中有一个分类变量.我想将整数ID分配给每个唯一值,并使用ID创建一个新的系列,从而有效地将字符串变量转换为整数变量.最紧凑/最有效的方法是什么?

I have a categorical variable in a series. I want to assign integer ids to each unique value and create a new series with the ids, effectively turning a string variable into an integer variable. What is the most compact/efficient way to do this?

推荐答案

您可以使用 pandas.factorize :

In [32]: s = pd.Series(['a','b','c'])

In [33]: labels, levels = pd.factorize(s)

In [35]: labels
Out[35]: array([0, 1, 2])

这篇关于将pandas系列从字符串转换为唯一的int id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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