joining two dataframes code example

Example 1: join on column pandas

# df1 as main df and use the feild from df2 and map it into df1

df1.merge(df2,on='columnName',how='left')

Example 2: Joins with another DataFrame

# Joins with another DataFrame

df.join(df2, df.name == df2.name, 'outer').select(
  df.name, df2.height).collect()
# [Row(name=None, height=80), Row(name=u'Bob', height=85), Row(
#   name=u'Alice', height=None)]

df.join(df2, 'name', 'outer').select('name', 'height').collect()
# [Row(name=u'Tom', height=80), Row(name=u'Bob', height=85), Row(
#   name=u'Alice', height=None)]

cond = [df.name == df3.name, df.age == df3.age]
df.join(df3, cond, 'outer').select(df.name, df3.age).collect()
# [Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]

df.join(df2, 'name').select(df.name, df2.height).collect()
# Row(name=u'Bob', height=85)]

df.join(df4, ['name', 'age']).select(df.name, df.age).collect()
# [Row(name=u'Bob', age=5)]

Example 3: python dataframe left join

>>> left.merge(right, on='user_id', how='left')

Example 4: dataframe concatenate

# Pandas for Python

df['col1 & col2'] = df['col1']+df['col2']

#Output
#col1	col2	col1 & col2
#A1		A2		A1A2
#B1		B2		B1B2

Example 5: combine df columns python

df["period"] = df["Year"] + df["quarter"]