2017-10-05 32 views
0

我有一個DF刪除無細胞,如何從一個數據幀在python

 contents values scoresBinned categories 
    0 Buy   484 (375, 500]  Bin 4 
    1 Sell   429 (375, 500]  Bin 4 
    2 Blanks  130 (125, 250]  Bin 2 
    3 A    108 (0, 125]   Bin 1 
    4 B    77 (0, 125]   Bin 1 
    5 F    2 (0, 125]   Bin 1 

,因爲我需要爲賓我的頭,我做的DF,樞

filter_df1=df[["contents","categories"]] 

pivot_df=filter_df1.pivot(columns="categories") 

print(pivot_df) 

       contents 
    categories Bin 1  Bin 2 Bin 4 
     0  None  None Buy 
     1  None  None Sell 
     2  None  Blanks None 
     3  A   None None 
     4  B   None None 
     5  F   None None 

我試過df.dropna (),但它會刪除整個行,

我期望df是,

  Bin 1  Bin 2 Bin 4 
      A   Blanks Buy 
      B     Sell 
      F   
+1

你怎麼輸出你的數據幀? – WhatsThePoint

+0

你想要的數據幀沒有意義。從數據框中刪除單個「單元格」是沒有意義的。你想要的輸出將數值放入它們以前不在的行中,即它完全忽略數據並返回一些毫無意義的東西。 –

+0

我編輯了我的問題,請檢查 – pyd

回答

1

您可以使用sorted,boolean indexingfillna來做到這一點。

pm = pivot_df.apply(sorted,key=pd.isnull) 
new = pm[~pd.isnull(pm).all(1)].fillna('') 

輸出:

 
      contents    
categories Bin 1 Bin 2 Bin 4 
0     A Blanks Buy 
1     B   Sell 
2     F    

說明

排序基於無會給

 
      contents    
categories Bin 1 Bin 2 Bin 4 
0     A Blanks Buy 
1     B None Sell 
2     F None None 
3    None None None 
4    None None None 
5    None None None 

現在選擇那些行,其中的所有行中值是不爲空。所以我們可以使用~pd.isnull(pm).all(1)(這裏~不是操作符,它會將真假轉換爲真,反之亦然)。這將給

 
0  True 
1  True 
2  True 
3 False 
4 False 
5 False 
dtype: bool 

後來boolen索引來選擇數據即pm[~pd.isnull(pm).all(1)]

 
     contents    
categories Bin 1 Bin 2 Bin 4 
0     A Blanks Buy 
1     B None Sell 
2     F None None 

fillna('')將填補沒有與''值。希望能幫助到你。

+0

它的工作,你能解釋這一行,新=下午[〜pd.isnull(pm).all(1)]。fillna('') – pyd

+0

確保檢查編輯。 – Dark