Pandas: Add Series to DataFrame ordered by column
<p>I am sure this was asked before, but I couldn't find it. I want to add a Series as a new column to the DataFrame. All the Series Index names are contained in one column of the DataFrame, but the Dataframe has more rows than the Series.</p>

<pre><code>DataFrame:
0 London 231
1 Beijing 328
12 New York 920
3 Singapore 1003

Series:
London AB
New York AC
Singapore B
</code></pre>

<p>and the result should look like</p>

<pre><code>0 London 231 AB
1 Beijing 328 NaN
12 New York 920 AC
3 Singapore 1003 B
</code></pre>

<p>How can I do this without loops? Thanks!</p>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">pandas.DataFrame.merge()</a></p>

<pre><code>df = pd.DataFrame({'A': [0,1,12,3], 'B': ['London', 'Beijing', 'New York', 'Singapore'], 'C': [231, 328, 920, 1003] })
    A          B     C
0   0     London   231
1   1    Beijing   328
2  12   New York   920
3   3  Singapore  1003

s = pd.Series(['AB', 'AC', 'B'], index=['London', 'New York', 'Singapore'])
London       AB
New York     AC
Singapore     B
dtype: object

df2 = pd.DataFrame({'D': s.index, 'E': s.values })
           D   E
0     London  AB
1   New York  AC
2  Singapore   B
</code></pre>

<p>Then, you can merge the two data frames:</p>

<pre><code>merged = df.merge(df2, how='left', left_on='B', right_on='D')
    A          B     C          D    E
0   0     London   231     London   AB
1   1    Beijing   328        NaN  NaN
2  12   New York   920   New York   AC
3   3  Singapore  1003  Singapore    B
</code></pre>

<p>You can drop columns <code>D</code></p>

<pre><code>merged = merged.drop('D', axis=1)
    A          B     C    E
0   0     London   231   AB
1   1    Beijing   328  NaN
2  12   New York   920   AC
3   3  Singapore  1003    B
</code></pre>

python pandas dataframe merge series