Home > Blockchain >  Pandas and Dictionary: How to get all unique values for each key?
Pandas and Dictionary: How to get all unique values for each key?

Time:10-07

I want to build a dictionary such that the value in the key-value pair is every unique value for that key.

Consider this example:

df = pd.DataFrame({'id': [1, 2, 3, 1, 2, 3], 'vals': ['a1', 'a2', 'a3', 'a2', 'a2a', 'a3a']})

# only yields last entry
dict(zip(df['id'], df['vals']))
# results
{1: 'a2', 2: 'a2a', 3: 'a3a'}

# expected value
{1: ['a1', 'a2'], 2: ['a2', 'a2a'], 3: ['a3', 'a3a']}

CodePudding user response:

Use:

result = df.groupby("id")["vals"].agg(list).to_dict()
print(result)

Output

{1: ['a1', 'a2'], 2: ['a2', 'a2a'], 3: ['a3', 'a3a']}

CodePudding user response:

You could use a dict comprehension, like so:

{k: group['vals'].tolist() for k, group in df.groupby('id')}

which outputs

{1: ['a1', 'a2'], 2: ['a2', 'a2a'], 3: ['a3', 'a3a']}

CodePudding user response:

print(df.groupby('id')['vals'].apply(lambda x: x.tolist()).to_dict())
  • Related