Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH] Coalesce fix #1042

Merged
merged 5 commits into from
Mar 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 additions & 13 deletions janitor/functions/coalesce.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,18 @@ def coalesce(
) -> pd.DataFrame:
"""Coalesce two or more columns of data in order of column names provided.

Given the list of column names, `coalesce` finds and returns the first
non-missing value from these columns, for every row in the input dataframe.
If all the column values are null for a particular row, then the
`default_value` will be filled in.
Given the variable arguments of column names,
`coalesce` finds and returns the first non-missing value
from these columns, for every row in the input dataframe.
If all the column values are null for a particular row,
then the `default_value` will be filled in.

If `target_column_name` is not provided,
then the first column is coalesced.

This method does not mutate the original DataFrame.

Example: Using `coalesce` with 3 columns, "a", "b" and "c".
Example: Use `coalesce` with 3 columns, "a", "b" and "c".

>>> import pandas as pd
>>> import numpy as np
Expand All @@ -34,13 +38,21 @@ def coalesce(
... "b": [2, 3, np.nan],
... "c": [4, np.nan, np.nan],
... })
>>> df.coalesce("a", "b", "c")
a b c
0 2.0 2.0 4.0
1 1.0 3.0 NaN
2 NaN NaN NaN

Example: Provide a target_column_name.

>>> df.coalesce("a", "b", "c", target_column_name="new_col")
a b c new_col
0 NaN 2.0 4.0 2.0
1 1.0 3.0 NaN 1.0
2 NaN NaN NaN NaN

Example: Providing a default value.
Example: Provide a default value.

>>> import pandas as pd
>>> import numpy as np
Expand Down Expand Up @@ -93,13 +105,8 @@ def coalesce(

if target_column_name is None:
target_column_name = column_names[0]
# bfill/ffill combo is faster than combine_first
outcome = (
df.filter(column_names)
.bfill(axis="columns")
.ffill(axis="columns")
.iloc[:, 0]
)

outcome = df.filter(column_names).bfill(axis="columns").iloc[:, 0]
if outcome.hasnans and (default_value is not None):
outcome = outcome.fillna(default_value)

Expand Down