Remove NaN 'Cells' without dropping the entire ROW (Pandas,Python3)

后端 未结 3 755
闹比i
闹比i 2020-12-06 18:40

Right now I have a DF like this

 Word       Word2          Word3
 Hello      NaN            NaN
 My         My Name        NaN
 Yellow     Yellow Bee     Yel         


        
3条回答
  •  盖世英雄少女心
    2020-12-06 19:06

    import numpy as np
    import pandas as pd
    import functools
    
    def drop_and_roll(col, na_position='last', fillvalue=np.nan):
        result = np.full(len(col), fillvalue, dtype=col.dtype)
        mask = col.notnull()
        N = mask.sum()
        if na_position == 'last':
            result[:N] = col.loc[mask]
        elif na_position == 'first':
            result[-N:] = col.loc[mask]
        else:
            raise ValueError('na_position {!r} unrecognized'.format(na_position))
        return result
    
    df = pd.read_table('data', sep='\s{2,}')
    
    print(df.apply(functools.partial(drop_and_roll, fillvalue='')))
    

    yields

         Word         Word2            Word3
    0   Hello       My Name  Yellow Bee Hive
    1      My    Yellow Bee                 
    2  Yellow  Golden Gates                 
    3  Golden                               
    4  Yellow     
    

提交回复
热议问题