combine two dataframes pandas based on column code example

Example 1: merge two dataframes based on column

df_outer = pd.merge(df1, df2, on='id', how='outer')

df_outer

Example 2: combining 2 dataframes pandas

df_3 = pd.concat([df_1, df_2])

Example 3: combine dataframes with two matching columns

merged_df = DF2.merge(DF1, how = 'inner', on = ['date', 'hours'])

Example 4: pandas create a new column based on condition of two columns

conditions = [
    df['gender'].eq('male') & df['pet1'].eq(df['pet2']),
    df['gender'].eq('female') & df['pet1'].isin(['cat', 'dog'])
]

choices = [5,5]

df['points'] = np.select(conditions, choices, default=0)

print(df)
     gender      pet1      pet2  points
0      male       dog       dog       5
1      male       cat       cat       5
2      male       dog       cat       0
3    female       cat  squirrel       5
4    female       dog       dog       5
5    female  squirrel       cat       0
6  squirrel       dog       cat       0

Example 5: combine two dataframe in pandas

# Stack the DataFrames on top of each other
vertical_stack = pd.concat([survey_sub, survey_sub_last10], axis=0)

# Place the DataFrames side by side
horizontal_stack = pd.concat([survey_sub, survey_sub_last10], axis=1)

Example 6: how to merge two pandas dataframes on a column

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')