merge columns pandas code example
Example 1: pandas merge two columns from different dataframes
df_merge_col = pd.merge(df1, df2, on='id')
Example 2: how to merge two dataframes
df_merge_col = pd.merge(df_row, df3, on='id')
df_merge_col
Example 3: 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 4: merge two columns pandas
df["period"] = df["Year"] + df["quarter"]
Example 5: how to concat on the basis of particular columns in pandas
In [6]: result = pd.concat(frames, keys=['x', 'y', 'z'])
Example 6: python add multiple columns to pandas dataframe
df[['new_column_1_name', 'new_column_2_name']] = pd.DataFrame([[np.nan, 'word']], index=df.index)
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
print(df)
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
df[['new_col_1', 'new_col_2', 'new_col_3']] = pd.DataFrame([[np.nan, 42, 'wow']], index=df.index)
print(df)
col_1 col_2 new_col_1 new_col_2 new_col_3
0 0 4 NaN 42 wow
1 1 5 NaN 42 wow
2 2 6 NaN 42 wow
3 3 7 NaN 42 wow
df['new_col_1'] = np.nan
df['new_col_2'] = 42
df['new_col_3'] = 'wow'