如何在python数据框中创建唯一的记录ID

时间:2017-07-03 06:07:34

标签: python dataframe indexing

我有一个数据框,我希望每个记录都有一个唯一的id(rec_id)。 像

这样的东西

picture of the troublesome df

我一直在使用rec_id = df.index,但索引不是唯一的 尝试使用df.reset_index()重置它。 也不好。

热烈欢迎任何建议。

BR Lasse

3 个答案:

答案 0 :(得分:1)

试试这个:

ds = ds.assign(rec_id=np.arange(len(ds))).reset_index(drop=True)

答案 1 :(得分:0)

也许是这样的

import pandas as pd

data = {'name': ['Jova', 'Mimi', 'Taty', 'Jessica', 'Alex'],
        'year': [2012, 2012, 2013, 2014, 2014],
        'docs': [40, 24, 19, 2, 3]}
df = pd.DataFrame(data, index = ['bg', 'ny', 'sd', 'sp', 'la'])

print (df)

print (df.name.unique())

答案 2 :(得分:0)

我在没有更漂亮的解决方案的情况下解决了这个问题。

    colle=ds.columns
    ds=ds.values
    ds=pd.DataFrame(ds)
    ds.columns=colle
    ds['rec_id']=ds.index