merge tables pandas code example
Example 1: pandas merge multiple dataframes
import pandas as pd
from functools import reduce
data_frames = [df1, df2, df3]
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['key_col'],
how='outer'), data_frames)
Example 2: merge dataframe pandas
>>> df1.merge(df2, left_on='lkey', right_on='rkey')
lkey value_x rkey value_y
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
Example 3: python - join two columns and transform it as index
df = DataFrame({'var_1':['a','b','c'], 'var_2':[1, 2, 3], 'var_3':['apple', 'banana', 'pear']})
cols = ['var_1', 'var_2']
df['combined'] = df[cols].apply(lambda row: ', '.join(row.values.astype(str)), axis=1)
df_i = df.set_index('combined')
df_i.index.names = [None]