Reputation: 33
I'm fairly new to python and was wondering whether it is possible to loop through a bunch of columns and replace missing values with another column that has the same name but with a suffix.
For example:
---obs---|---col1---|---col2---|---col1_suffix---|---col2_suffix---|
----1-----|---NaN---|----50-----|------20----------| -----60------------
----2-----|---200---|----NaN----|------30---------| ------100---------
Will want to loop through from col1 to up to colN and replace the NaN with the value in col1_suffix up to colN_suffix. So in above example, col1 NaN will be replaced with a value of 20 and col2 NaN will be replaced with 100.
Upvotes: 1
Views: 2067
Reputation: 164803
Assuming you are using panda
, you could do this:
for col in ['col1', 'col2']:
df[col] = df[col].fillna(df[col+'_suffix'])
A more generic version:
for col in df.columns:
if col+'_suffix' in df.columns:
df[col] = df[col].fillna(df[col+'_suffix'])
Upvotes: 3