gpt4 book ai didi

python - pandas 中值的唯一从零开始的 id

转载 作者:行者123 更新时间:2023-11-28 20:25:22 25 4
gpt4 key购买 nike

我在带有标识符列的 DataFrame 中有一些数据。

data = DataFrame({'id' : [50,50,30,10,50,50,30]})

对于每个唯一 ID,我想提出一个新的唯一标识符。我希望 ID 是从 0 开始的连续整数。这是我目前所拥有的:

unique = data[['id']].drop_duplicates()   
unique['group'] = np.arange(len(unique))
unique.set_index('id')
data = data.merge(unique, 'inner', on = 'id')

这可行,但看起来有点脏。有没有更好的办法?

最佳答案

这就是pandas.factorize做:

data = pd.DataFrame({'id' : [50,50,30,10,50,50,30]})
print pd.factorize(data.id)[0]

输出:

[0 0 1 2 0 0 1]

numpy.unique也可以这样做:

import numpy as np
print np.unique([50,50,30,10,50,50,30], return_inverse=True)[1]

输出:

array([2, 2, 1, 0, 2, 2, 1])

numpy.unique 输出的索引是按值排序的,所以最小值 10 被分配给索引 0。如果你想使用 factorize 得到这个结果,设置sort 参数为 True:

pandas.factorize(data.id, sort=True)[0]

关于python - pandas 中值的唯一从零开始的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15376475/

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