Skip to content Skip to sidebar Skip to footer

Skip Nan And Shift Elements In A Pandas Dataframe Row

I have a dataframe like this [![Dataframe looks like this][1]: https://i.stack.imgur.com/R7GmM.png Now I want to skip nan's and so that data shift towards left i.e. [![formatted da

Solution 1:

Here is one method:

Starting from your dataframe named df:

AB    C    D
0a  NaN    c  NaN
1b  NaN    ba2  c  NaN  NaN    d
3  d    ab    c

apply these line:

shifted_df = df.apply(lambda x: pd.Series(x.dropna().values), axis=1).fillna('')
shifted_df.columns = df.columns

And you get your resulting shifted_df dataframe:

>>> shifted_df
   AB  C  D
0a  c      
1bba2  c  d      
3  d  ab  c

Post a Comment for "Skip Nan And Shift Elements In A Pandas Dataframe Row"