From 30c1a3811f96b9947a770a00e2753af2c0cecfe2 Mon Sep 17 00:00:00 2001 From: "D. Debnath" Date: Thu, 23 Jan 2025 21:22:49 +0530 Subject: [PATCH] Update nsfg.py to fix FutureWarning Fix warning: ThinkStats2/code/nsfg.py:66: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method. The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy. For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object. --- code/nsfg.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/code/nsfg.py b/code/nsfg.py index 3d28262f0..40f8e7e30 100644 --- a/code/nsfg.py +++ b/code/nsfg.py @@ -65,12 +65,17 @@ def CleanFemPreg(df): # replace 'not ascertained', 'refused', 'don't know' with NaN na_vals = [97, 98, 99] - df.birthwgt_lb.replace(na_vals, np.nan, inplace=True) - df.birthwgt_oz.replace(na_vals, np.nan, inplace=True) - df.hpagelb.replace(na_vals, np.nan, inplace=True) - - df.babysex.replace([7, 9], np.nan, inplace=True) - df.nbrnaliv.replace([9], np.nan, inplace=True) + df.replace( + to_replace={ + "birthwgt_lb": na_vals, + "birthwgt_oz": na_vals, + "hpagelb": na_vals, + "babysex": [7, 9], + "nbrnaliv": [9], + }, + value=np.nan, + inplace=True, + ) # birthweight is stored in two columns, lbs and oz. # convert to a single column in lb