简体   繁体   中英

Create a dictionary of unique values of a column in a dataframe in pandas

I have a dataframe:

import pandas as pd
df = pd.DataFrame({ 
'ID': ['ABC', 'ABC', 'ABC', 'XYZ', 'XYZ', 'XYZ'], 
'value': [100, 120, 130, 200, 190, 210],
'value2': [2100, 2120, 2130, 2200, 2190, 2210],   
'state': ['init','mid', 'final', 'init', 'mid', 'final'], 
})

I want to create dictionary of unique values of the Column 'ID'. I can extract the unique values by:

df.ID.unique()

But that gives me a list. I want the output to be a dictionary, which looks like this:

dict = {0:'ABC', 1: 'XYZ'}

If the number of unique entries in the column is n, then the keys should start at 0 and go till n-1. The values should be the names of unique entries in the column

The actual dataframe has 1000s of rows and is often updated. So I cannot maintain the dict manually.

Try this. -

dict(enumerate(df.ID.unique()))
{0: 'ABC', 1: 'XYZ'}

If you want to get unique values for a particular column in dict, try:

val_dict = {idx:value for idx , value in enumerate(df["ID"].unique())}

Output while printing val_dict

{0: 'ABC', 1: 'XYZ'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM