Updating column in pandas DataFrame based on another column and a separate dictionary
<p>I am trying to make a piece of my code run quicker.</p>

<p>I have two dataframes of different sizes, A and B.  I have a dictionary of ages too called age_dict.</p>

<p>A contains 100 rows, and B contains 200 rows.  They both use an index starting at 0. They both have two columns which are "Name" and "Age"</p>

<p>The dictionary keys are names and their values are ages.  All keys are unique, there are no duplicates</p>

<p>{'John':20,'Max':25,'Jack':30}</p>

<p>I want to find the names in each DataFrame and assign them the age from the dictionary.  I achieve this using the following code (I want to return a new DataFrame and not amend the old one):</p>

<pre><code>def age(df):
   new_df = df.copy(deep=True)
   i = 0
   while i &lt; len(new_df['Name']):
       name = new_df['Name'][i]
       age = age_dict[name]
       new_df['Age'][i] = age
       i += 1
   return new_df

new_A = age(A)
new_B = age(B)
</code></pre>

<p>This code takes longer than I want it to, so I'm wondering if pandas has an easier way to do this instead of me looping through each row?</p>

<p>Thank you!</p>