DataFusion supports the following join variants via the method :py:func:`~datafusion.dataframe.DataFrame.join`
- Inner Join
- Left Join
- Right Join
- Full Join
- Left Semi Join
- Left Anti Join
For the examples in this section we'll use the following two DataFrames
.. ipython:: python
from datafusion import SessionContext
ctx = SessionContext()
left = ctx.from_pydict(
{
"customer_id": [1, 2, 3],
"customer": ["Alice", "Bob", "Charlie"],
}
)
right = ctx.from_pylist([
{"id": 1, "name": "CityCabs"},
{"id": 2, "name": "MetroRide"},
{"id": 5, "name": "UrbanGo"},
])
When using an inner join, only rows containing the common values between the two join columns present in both DataFrames will be included in the resulting DataFrame.
.. ipython:: python
left.join(right, left_on="customer_id", right_on="id", how="inner")
The parameter join_keys specifies the columns from the left DataFrame and right DataFrame that contains the values
that should match.
A left join combines rows from two DataFrames using the key columns. It returns all rows from the left DataFrame and matching rows from the right DataFrame. If there's no match in the right DataFrame, it returns null values for the corresponding columns.
.. ipython:: python
left.join(right, left_on="customer_id", right_on="id", how="left")
A full join merges rows from two tables based on a related column, returning all rows from both tables, even if there is no match. Unmatched rows will have null values.
.. ipython:: python
left.join(right, left_on="customer_id", right_on="id", how="full")
A left semi join retrieves matching rows from the left table while omitting duplicates with multiple matches in the right table.
.. ipython:: python
left.join(right, left_on="customer_id", right_on="id", how="semi")
A left anti join shows all rows from the left table without any matching rows in the right table, based on a the specified matching columns. It excludes rows from the left table that have at least one matching row in the right table.
.. ipython:: python
left.join(right, left_on="customer_id", right_on="id", how="anti")
It is common to join two DataFrames on a common column name. Starting in
version 51.0.0, datafusion-python` will now drop duplicate column names by
default. This reduces problems with ambiguous column selection after joins.
You can disable this feature by setting the parameter drop_duplicate_keys
to False.
.. ipython:: python
left = ctx.from_pydict(
{
"id": [1, 2, 3],
"customer": ["Alice", "Bob", "Charlie"],
}
)
right = ctx.from_pylist([
{"id": 1, "name": "CityCabs"},
{"id": 2, "name": "MetroRide"},
{"id": 5, "name": "UrbanGo"},
])
left.join(right, "id", how="inner")
In contrast to the above example, if we wish to get both columns:
.. ipython:: python
left.join(right, "id", how="inner", drop_duplicate_keys=False)