0

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
John Stud
  • 1,506
  • 23
  • 46

1 Answers1

2

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
BENY
  • 317,841
  • 20
  • 164
  • 234