Python Program to perform cross join in Pandas
Last Updated :
10 Jul, 2020
In Pandas, there are parameters to perform left, right, inner or outer merge and join on two DataFrames or Series. However there’s no possibility as of now to perform a cross join to merge or join two methods using how="cross"
parameter.
Cross Join :
Example 1:
The above example is proven as follows
import pandas as pd
data1 = { 'A' : [ 1 , 2 ]}
data2 = { 'B' : [ 'a' , 'b' , 'c' ]}
df = pd.DataFrame(data1, index = [ 0 , 1 ])
df1 = pd.DataFrame(data2, index = [ 2 , 3 , 4 ])
df[ 'key' ] = 1
df1[ 'key' ] = 1
result = pd.merge(df, df1, on = 'key' ).drop( "key" , 1 )
result
|
DataFrame 1:
DataFrame 2 :
Output :
Example 2:
Cross join on two DataFrames for user and product.
import pandas as pd
data1 = { 'Name' : [ "Rebecca" , "Maryam" , "Anita" ],
'UserID' : [ 1 , 2 , 3 ]}
data2 = { 'ProductID' : [ 'P1' , 'P2' , 'P3' , 'P4' ]}
df = pd.DataFrame(data1, index = [ 0 , 1 , 2 ])
df1 = pd.DataFrame(data2, index = [ 2 , 3 , 6 , 7 ])
df[ 'key' ] = 1
df1[ 'key' ] = 1
result = pd.merge(df, df1, on = 'key' ).drop( "key" , 1 )
result
|
DataFrame 1:
DataFrame 2 :
Output :
Example 3:
import pandas as pd
data1 = { 'col 1' : [ 0 , 1 ],
'col 2' : [ 2 , 3 ]}
data2 = { 'col 3' : [ 5 , 6 ],
'col 4' : [ 7 , 8 ]}
df = pd.DataFrame(data1, index = [ 0 , 1 ])
df1 = pd.DataFrame(data2, index = [ 2 , 3 ])
df[ 'key' ] = 1
df1[ 'key' ] = 1
result = pd.merge(df, df1, on = 'key' ).drop( "key" , 1 )
result
|
DataFrame 1:
DataFrame 2 :
Output :
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...