Search code examples
pythonarrayspandasdataframearrange-act-assert

Python DataFrame: rearrange the objects and empty values


I have a Python DataFrame with 20000+ values as below. And I want to efficiently rearrange df with NaN goes after string of values.

    IT1     IT2     IT3     IT4     IT5     IT6
0   qwe     NaN     NaN     rew     NaN     NaN
1   NaN     NaN     sdc     NaN     NaN     wer
2   NaN     NaN     NaN     NaN     NaN     NaN
3   asd     fsc     ws      zd      ews     df 
.....

to

    IT1     IT2     IT3     IT4     IT5     IT6
0   qwe     rew     NaN     NaN     NaN     NaN
1   sdc     wer     NaN     NaN     NaN     NaN     
2   NaN     NaN     NaN     NaN     NaN     NaN
3   asd     fsc     ws      zd      ews     df 
.....

So each row can have no values like index = 2, or all values like index = 3. Is there a way to efficiently rearrange my dataframe df? Thanks in advance


Solution

  • One way, albeit slowly, apply, dropna, and tolist:

     df.apply(lambda x: pd.Series(x.dropna().tolist()),1)\
       .set_axis(df.columns, axis=1, inplace=False)
    

    Output:

       IT1  IT2  IT3  IT4  IT5  IT6
    0  qwe  rew  NaN  NaN  NaN  NaN
    1  sdc  wer  NaN  NaN  NaN  NaN
    2  NaN  NaN  NaN  NaN  NaN  NaN
    3  asd  fsc   ws   zd  ews   df