Pandas:根据模式自动生成增量ID

2024-04-20 04:01:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个数据框,其中不断添加各种用户(姓名、电话号码、地址…)。现在,我需要一个函数,一旦一个新的、不存在的用户被添加到数据帧中,它就会自动生成一个ID

第一个用户应该获得ID U000001,第二个用户应该获得ID U000002,依此类推

最好的方法是什么


Tags: 数据方法函数用户id地址电话号码姓名
1条回答
网友
1楼 · 发布于 2024-04-20 04:01:51

如果我理解正确,主要问题是前导零。i、 e.不能只增加上一个ID,因为类型转换“0001”只给出1而不是0001。如果我错了,请纠正我

不管怎样,这是我想到的。这比你可能需要的要详细得多,但我想确保我的逻辑是清楚的

def foo(previous):
    """
    Takes in string of format 'U#####...'
    Returns incremented value in same format.
    Returns None if previous already maxed out (i.e. 'U9999')
    """
    value_str = previous[1:]    # chop off 'U'
    value_int = int(value_str)  # get integer value

    new_int = value_int + 1     # increment

    new_str = str(new_int)      # turn back into string

    # return None if exceeding character limit on ID
    if len(new_str) > len(value_str):
        print("Past limit")
        return(None)

    # add leading zeroes
    while(len(new_str) < len(value_str)):
        new_str = '0' + new_str

    # add 'U' and return
    return('U' + new_str)

如果我能澄清任何事情,请告诉我!这里有一个脚本可以用来测试它:

# test
current_id = 'U0001'
while(True):
    current_id = foo(current_id)
    print(current_id)
    if current_id == None:
        break

相关问题 更多 >