Create pandas dataframe column from another column that has dictionary keys
<p>I have dataframe and a dict. These look like,</p>

<pre><code>import pandas as 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'}
</code></pre>

<p>The values of df1['first'] represent the key values of the dict.</p>

<p>I would like to add a second column to the data frame called df1['second'] so the dict relationship is maintained to get the following dataframe,</p>

<pre><code>    first    last
0    john  anderson
1  oliver     smith
2   sarah   shively
</code></pre>

<p>Now, I could just iterate over the dataframe values, like so,</p>

<pre><code>df1['last'] = [ df1_map[i] for i in list(df1['first'])]
</code></pre>

<p>I was wondering if pandas support a vectorized implementation / function that can do this without iterating over rows of the df</p>

<p>You can just map dictionaries values directly to the keys with:</p>

<pre><code>df1['last'] = df1['first'].map(df1_map)
</code></pre>

<p>result is:</p>

<pre><code>Out[6]: 
    first      last
0    john  anderson
1  oliver     smith
2   sarah   shively
</code></pre>

python pandas