gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:35 24 4
gpt4 key购买 nike

数据框 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com