Home > Net >  If col is empty string, make adjacent column empty as well
If col is empty string, make adjacent column empty as well

Time:09-30

Consider this sample df:

colAnum    colB   colCnum    colD
123        House  456        Book
           Car    789        Table
891        Chair             Porch

I am trying to roll through this df and if the "num" column is an empty string, then make the adjacent column, to the right, empty as well.

This is the expected output:

colAnum    colB   colCnum    colD
123        House  456        Book
                  789        Table
891        Chair             

I attempted this with variations on this:

for idx, col in enumerate(df.columns):
    if df.iloc[idx, col] == '':
       df[idx 1,col] == ''

I am sure I am missing something simple to make this occur, but cannot work my way around it.

CodePudding user response:

Try with shift with mask

out = df.mask(df.eq('').shift(axis=1).fillna(False),'')
  colAnum   colB colCnum   colD
0   123.0  House   456.0   Book
1                  789.0  Table
2   891.0  Chair               

CodePudding user response:

Just loop over the column names, checking if it ends with num. Then use df.loc to set the related column without the num suffix when the column contains an empty string.

for col in df.columns:
    if col.endswith("num"):
        othercol = col[:-3] # colAnum => colA
        df.loc[df[col].eq(''), othercol] = ""
  • Related