Skip to content

Commit 6d072ea

Browse files
authored
Do not overwrite the caller's DataFrame when FilterSelect imputes nulls (#1080)
1 parent b029a5d commit 6d072ea

2 files changed

Lines changed: 31 additions & 7 deletions

File tree

‎causalml/feature_selection/filters.py‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -514,21 +514,22 @@ def _filter_D_one_feature(
514514

515515
totalSize = len(data.index)
516516

517-
# impute null if enabled
517+
# impute null if enabled, without writing the imputed values back into the caller's data
518+
x = data[feature_name].values
518519
if null_impute is not None:
519-
data[feature_name] = SimpleImputer(
520-
missing_values=np.nan, strategy=null_impute
521-
).fit_transform(data[feature_name].values.reshape(-1, 1))
520+
x = (
521+
SimpleImputer(missing_values=np.nan, strategy=null_impute)
522+
.fit_transform(x.reshape(-1, 1))
523+
.ravel()
524+
)
522525
elif data[feature_name].isna().any():
523526
raise Exception(
524527
"Null value(s) present in column '{}'. Please impute the null value or use null_impute parameter "
525528
"provided.".format(feature_name)
526529
)
527530

528531
# drop duplicate edges in pq.cut result to avoid issues
529-
x_bin = pd.qcut(
530-
data[feature_name].values, n_bins, labels=False, duplicates="drop"
531-
)
532+
x_bin = pd.qcut(x, n_bins, labels=False, duplicates="drop")
532533

533534
d_children = 0
534535

‎tests/test_feature_selection.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,29 @@ def test_filter_kl(generate_classification_data):
6767
assert imp["score"].values[0] >= imp["score"].values[1]
6868

6969

70+
@pytest.mark.parametrize("method", ["KL", "ED", "Chi"])
71+
def test_filter_d_null_impute_leaves_input_unchanged(
72+
generate_classification_data, method
73+
):
74+
np.random.seed(RANDOM_SEED)
75+
df, X_names = generate_classification_data()
76+
df.loc[df.index[:10], X_names[0]] = np.nan
77+
original = df.copy()
78+
79+
imp = FilterSelect().get_importance(
80+
df,
81+
X_names,
82+
CONVERSION,
83+
method,
84+
treatment_group="treatment1",
85+
null_impute="mean",
86+
)
87+
88+
assert imp.shape[0] == len(X_names)
89+
# The imputation is only used for binning: the caller's NaNs are kept
90+
pd.testing.assert_frame_equal(df, original)
91+
92+
7093
@pytest.mark.parametrize("method", ["LR", "KL", "ED", "Chi"])
7194
def test_filter_rejects_non_binary_outcome(generate_classification_data, method):
7295
"""Regression test for uber/causalml#349.

0 commit comments

Comments
 (0)