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