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>

<ol>
<li>set <code>index</code> to city names for both <code>df</code> and <code>series</code></li>
<li>combine via pandas <code>merge</code></li>
</ol>

<hr>

<pre><code>import pandas as pd

cities = ['London', 'Beijing', 'New York', 'Singapore']

df_data = {
    'col_1': [0,1,12,3],
    'col_2': [231, 328, 920, 1003],
}

df = pd.DataFrame(df_data, index=cities)

cities2 = ['London','New York','Singapore']

series = pd.Series(['AB', 'AC', 'B'], index=cities2)


combined = pd.merge(
    left=df,
    right=pd.DataFrame(series),
    how='left',
    left_index=True,
    right_index=True
)

print combined
</code></pre>

<hr>

<p>OUTPUT:</p>

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

python pandas dataframe merge series