John Stud
John Stud

Reputation: 1779

How to map multi-valued dict into multiple Pandas columns?

Following a related example which does not quite get the right answer (but is close): Python Pandas Assign a Dictionary Value to a Dataframe Column Based on Dictionary Key

I am looking for a way to do, ideally in a one-liner, map a dictionary key to my dataframe column. If the keys match, we should unpack each value into its respective column.

import pandas as pd
d1 = {1231: 'val1, val2, val3',
      1232: 'val1a, val2a, val3a'}

df = pd.DataFrame({'key': [1231, 1232]})
df[['val1', 'val2', 'val3']] = df['key'].apply(lambda x: d1.get(x))[0].split(', ')
df

# this will map the same values repeatedly
# and will break if the index is altered or removed

Upvotes: 0

Views: 1181

Answers (1)

BENY
BENY

Reputation: 323226

Try with map then str.split

df[['val1', 'val2', 'val3']] = df['key'].map(d1).str.split(', ',expand=True).values
df
    key   val1   val2   val3
0  1231   val1   val2   val3
1  1232  val1a  val2a  val3a

Upvotes: 2

Related Questions