Pandas How To Uncategorized How to join dataframe with series

How to join dataframe with series

You can join a dataframe with a series in pandas using the merge method or the concat function. The default behavior is to align the series index with the dataframe index and perform a left join:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
s = pd.Series([7, 8, 9], name='C')

result = df.merge(pd.DataFrame(s), left_index=True, right_index=True)

# or


result = pd.concat([df, s], axis=1)

If you want to join the series to a specific column in the dataframe, you can reset the index of the series to match the values in the specified dataframe column, then merge on that column:

s.reset_index(inplace=True)
s.columns = ['B', 'C']

result = df.merge(s, on='B')

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post