簡體   English   中英

將數據從數據框的頂部移到底部(df的列的長度索引不同)

[英]Move the data from the top to the bottom of the dataframe (df that has varying length index for its columns)

我的df如下圖所示

Index   Col1   Col2  Col3  Col4   Col5      
 0      12     121   346   abc    747
 1      156    121   146   68     75967
 2      234   121    346   567   
 3      gj    161    646   
 4      214   171   
 5      fhg   

.......

我想使數據框顯示為具有空值的列,這些列將其數據移動/移動到數據框的底部。 例如,它應該看起來像:

Index   Col1   Col2  Col3  Col4   Col5      
 0      12     
 1      156    121   
 2      234   121    346   
 3      gj    121    146   abc 
 4      214   161    346   68    747
 5      fhg   171    646   567   75967

我已經考慮過轉變和/或辯護的思路。 但是,對於大型數據框,不確定如何以最有效的方式完成

您可以使用一點變化證明與非數值還在努力功能:

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:
        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)
    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

arr = justify(df.values, invalid_val=np.nan, side='down', axis=0)

df = pd.DataFrame(arr, columns=df.columns, index=df.index).astype(df.dtypes)
print (df)
  Col1 Col2 Col3 Col4   Col5
0   12  NaN  NaN  NaN    NaN
1  156  121  NaN  NaN    NaN
2  234  121  346  NaN    NaN
3   gj  121  346  567    NaN
4  214  121  346  567  75967
5  fhg  121  346  567  75967

我試過了

t=df.isnull().sum()
for val in zip(t.index.values,t.values):
    df[val[0]]=df[val[0]].shift(val[1])
print df

輸出:

   Index Col1   Col2   Col3 Col4  Col5      
0      0   12    NaN    NaN  NaN         NaN
1      1  156  121.0    NaN  NaN         NaN
2      2  234  121.0  346.0  NaN         NaN
3      3   gj  121.0  146.0  abc         NaN
4      4  214  161.0  346.0   68       747.0
5      5  fhg  171.0  646.0  567     75967.0

注意:在這里我使用了循環,可能不是更好的解決方案,但是它將為您提供解決此問題的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM