2017-11-08 3 views
0

私は以下のデータフレームを持っており、appleという列が見つかった場合は列のフルーツを検索し、すべての行を表示したいと考えています。pandasはデータフレーム列の値を検索します

Before : 
    number fruits  purchase 
    0  apple  yes 
      mango 
      banana 
    1  apple  no 
      cheery  
    2  mango  yes 
      banana 
    3  apple  yes 
      orange 
    4  grapes no 
      pear 

After:    
    number fruits  purchase 
    0  apple  yes 
      mango 
      banana 
    1  apple  no 
      cheery  
    3  apple  yes 
      orange 
+0

果物の列の種類はリストまたは文字列ですか? – Wen

+0

果物の列型がオブジェクト – Sun

答えて

0

あなたはインデックスとして'number'を使用しているので、私はそれを前提とするつもりだように見えます。

'apple'が存在している数字、およびそれらへのスライスを取得: 'りんご' を含むフィルタグループに

idx = df.index[df.fruits == 'apple'] 
df.loc[idx] 
+0

私はインデックスとして数字を使用していません。 – Sun

1

使用groupbyfilterを:

df['number'] = df['number'].ffill() 

df.groupby('number').filter(lambda x: (x['fruits'] == 'apple').any()) 

df_out.assign(number = df_out['number'].mask(df.number.duplicated()))\ 
    .replace(np.nan,'') 

出力:

number fruits purchase 
0  0 apple  yes 
1   mango   
2   banana   
3  1 apple  no 
4   cheery   
7  3 apple  yes 
8   orange   
関連する問題