如何将Nan值移动到所有列的结尾

时间:2018-10-03 07:24:34

标签: python pandas dataframe

我有这样的df,

A     B     C
a     NaN   NaN
b     NaN   NaN
c     NaN   NaN
NaN   a     NaN
NaN   b     NaN
NaN   c     NaN
NaN   NaN   a
NaN   NaN   b
NaN   NaN   c

所需的输出

A   B   C
a   a   a
b   b   b
c   c   c
NaN NaN NaN 
NaN NaN NaN 
NaN NaN NaN 
NaN NaN NaN 
NaN NaN NaN 
NaN NaN NaN

2 个答案:

答案 0 :(得分:1)

您可以使用稍作改动的justify函数:

def justify(a, invalid_val=0, axis=1, side='left'):    
    """
    Justifies a 2D array

    Parameters
    ----------
    A : ndarray
        Input array to be justified
    axis : int
        Axis along which justification is to be made
    side : str
        Direction of justification. It could be 'left', 'right', 'up', 'down'
        It should be 'left' or 'right' for axis=1 and 'up' or 'down' for axis=0.

    """

    if invalid_val is np.nan:
        #change to notnull
        mask = pd.notnull(a)
    else:
        mask = a!=invalid_val
    justified_mask = np.sort(mask,axis=axis)
    if (side=='up') | (side=='left'):
        justified_mask = np.flip(justified_mask,axis=axis)
    #change dtype to object
    out = np.full(a.shape, invalid_val, dtype=object)  
    if axis==1:
        out[justified_mask] = a[mask]
    else:
        out.T[justified_mask.T] = a.T[mask.T]
    return out

df = pd.DataFrame(justify(df.values, invalid_val=np.nan, side='up', axis=0), 
                  columns=df.columns)
print (df)
     A    B    C
0    a    a    a
1    b    b    b
2    c    c    c
3  NaN  NaN  NaN
4  NaN  NaN  NaN
5  NaN  NaN  NaN
6  NaN  NaN  NaN
7  NaN  NaN  NaN
8  NaN  NaN  NaN

答案 1 :(得分:1)

您可以创建一个布尔掩码,然后使用argsort对布尔掩码进行排序,并为最终数组建立索引:

A = df.isnull().values

out = df.values[np.argsort(A, axis=0, kind='mergesort'), np.arange(A.shape[1])]

array([['a', 'a', 'a'],
       ['b', 'b', 'b'],
       ['c', 'c', 'c'],
       [nan, nan, nan],
       [nan, nan, nan],
       [nan, nan, nan],
       [nan, nan, nan],
       [nan, nan, nan],
       [nan, nan, nan]], dtype=object)

并重新创建DataFrame:

pd.DataFrame(out, columns=df.columns)

     A    B    C
0    a    a    a
1    b    b    b
2    c    c    c
3  NaN  NaN  NaN
4  NaN  NaN  NaN
5  NaN  NaN  NaN
6  NaN  NaN  NaN
7  NaN  NaN  NaN
8  NaN  NaN  NaN