python - Pandas 数据帧 : create new ID variable based on number of modalities of an existing one

标签 python python-3.x pandas dataframe

数据框 df 包含一个 ID 变量,其中包含观察组的 ID。但 ID 值有“漏洞”(可以是 1、3、4、7,不能是 0、2、5、6)。

df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6 ], 'b': [7, 8 , 9, 10, 11, 12],
                   'id': [1, 4, 4, 7, 3, 1]})

   a   b  id
0  1   7   1
1  2   8   4
2  3   9   4
3  4  10   7
4  5  11   3
5  6  12   1

我的目标是用新的 ID 变量替换现有的 ID 变量,从 0 开始到原始 ID 变量中的最大 ID 数,例如。

df2 = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6 ], 'b': [7, 8 , 9, 10, 11, 12],
                    'id': [0, 2, 2, 3, 1, 0]})

   a   b  id
0  1   7   0
1  2   8   2
2  3   9   2
3  4  10   3
4  5  11   1
5  6  12   0

知道如何做到这一点吗?

感谢您的宝贵时间!

最佳答案

pd.factorize支持这个:

df['id'] = pd.factorize(df['id'], sort=True)[0]

#    a   b  id
# 0  1   7   0
# 1  2   8   2
# 2  3   9   2
# 3  4  10   3
# 4  5  11   1
# 5  6  12   0

关于python - Pandas 数据帧 : create new ID variable based on number of modalities of an existing one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847934/

相关文章:

python - 重复计数循环(n*n码性能)

python-3.x - 将辅助类与 Snowflake 一起使用会导致连接问题

python - 带有空间的类属性

python - 基于数据框的两列创建网络并将其组件 ID 添加为新的聚合列

python - 每日数据,每 3 天重新采样,有效计算尾随 5 天

python - Pandas 循环遍历数据框列表和更改索引

python - 用于 python 脚本的 iTunes API

连接时 Python openSSL 服务器崩溃 - SSL 出现奇怪错误

python - TFLite 转换不支持的操作 : CropAndResize

python - 如何在 python 中的列表中搜索可能不存在的内容?