python - Create pandas dataframe column from another column that has dictionary keys -
i have dataframe , dict. these like,
import pandas pd df1 = pd.dataframe({'first':['john','oliver','sarah']}) df1_map = {'john': 'anderson', 'oliver': 'smith', 'sarah' : 'shively'} print (df1) print (df1_map) first 0 john 1 oliver 2 sarah {'oliver': 'smith', 'sarah': 'shively', 'john': 'anderson'}
the values of df1['first'] represent key values of dict.
i add second column data frame called df1['second'] dict relationship maintained following dataframe,
first last 0 john anderson 1 oliver smith 2 sarah shively
now, iterate on dataframe values, so,
df1['last'] = [ df1_map[i] in list(df1['first'])]
i wondering if pandas support vectorized implementation / function can without iterating on rows of df
you can map dictionaries values directly keys with:
df1['last'] = df1['first'].map(df1_map)
result is:
out[6]: first last 0 john anderson 1 oliver smith 2 sarah shively
Comments
Post a Comment