Vlad is Glad Vlad is Glad - 1 year ago 93
Python Question

Left Outer Join a Data frame with a Series object by key on data frame, index on series

Is it possible to join a series object to a dataframe without having to turn the series into a dataframe?

Currently, I calculate something, get a series as a result, and have to turn the series into a dataframe to merge the two:

clicked_series = p.clicked.sum();
temp_df = pd.DataFrame({'ad_id':clicked_series.index, 'clicks':clicked_series.values})
full_df = pd.merge(full_df, temp_df, on='ad_id', how='left')

Is it possible to conduct a left outer join on the series and dataframe directly, without having to create a temporary data frame?

Answer Source

use reindex

full_df['clicks'] = clicked_series.reindex(full_df.ad_id).values

old answers

Use join
technically, I'm still converting to a pd.DataFrame but...

clicked_series = p.clicked.sum();
full_df = full_df.join(clicked_series.to_frame('clicks'), on='ad_id', how='left')

Another option is to use pd.concat. But this will look like an outer join.

           clicked_series.rename('clicks')], axis=1).reset_index()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download