xxxxxxxxxx
# First dataframe with three columns
dlist=["vx","vy","vz"]
df=pd.DataFrame(columns=dlist)
df["vx"]=df1["v2x"]
df["vy"]=df1["v2y"]
df["vz"]=df1["v2z"]
# second dataframe with three columns
dlist=["vx","vy","vz"]
df0=pd.DataFrame(columns=dlist)
df0["vx"]=df2["v1x"]
df0["vy"]=df2["v1y"]
df0["vz"]=df2["v1z"]
# Here with concat we can create new dataframe with garther both in one
# YOU CAN PUT SOME VALUES IN EACH AND CHECK IT
# WHAT INSIDE THE CONCAT MUST BE A LIST OF DATAFRAME
v = pd.concat([df,df0])
xxxxxxxxxx
df_outer = pd.merge(df1, df2, on='id', how='outer') #here id is common column
df_outer
xxxxxxxxxx
#suppose you have two dataframes df1 and df2, and
#you need to merge them along the column id
df_merge_col = pd.merge(df1, df2, on='id')
xxxxxxxxxx
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
xxxxxxxxxx
# Merging 3 or more dataframes base on a common column
import pandas as pd
from functools import reduce
#Create a list of df to combine
list_of_df = [df_1,df_2,df_3]
#merge them together
df_combined = reduce(lambda left,right: pd.merge(left,right,on='common column'), list_of_df)
xxxxxxxxxx
import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')
xxxxxxxxxx
merged_df = left_df.merge(right_df, how='inner', left_on=["A", "B"], right_on=["A2","B2"])
This allows f to be a user-defined function with multiple input values and uses column names rather than numeric indices to access the columns
xxxxxxxxxx
df['new_column'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)