0
$\begingroup$

I need to create a primary key based in string columns in my dataframe

Month       Name                   ID
01/01/2020  FileName1 - Example    1
01/02/2020  FileName2 - Example    2
01/03/2020  FileName3 - Example    3

I'm using the hash, but its generating the largest values, I would like that ID was the integer numbers. This is my code

all_data['unique_id'] = all_data._ID.map(hash)

where _ID is :

all_data['_ID'] = all_data['Month'].astype(str) + all_data['Name']

This group by return 0 for all rows

all_data['sequence']=all_data.groupby('_ID').cumcount()
$\endgroup$
1
  • $\begingroup$ The groupby returns all 0 means your unique id is in fact unique for every rows. $\endgroup$ – Quang Hoang Feb 11 at 23:53
0
$\begingroup$

Use pd.factorzie:

all_data['unique_id'] = pd.factorize(all_data['_ID'])[0]
$\endgroup$
1
$\begingroup$

You could simply drop the index to create and use it as a primary key column.

all_data.reset_index(inplace=True)
all_data.head()

all_data_result

$\endgroup$
1
  • $\begingroup$ Month =["01/01/2020","01/02/2020","01/03/2020"] Name=["FileName1 - Example","FileName2 - Example","FileName3 - Example"] ID=[1,2,3] df=pd.DataFrame({'Month':Month,'Name':Name,'ID':ID}) df=df.set_index('ID') print(df.index) $\endgroup$ – Golden Lion Feb 15 at 22:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.