2016-09-23 86 views
1

我有一個dataframe dfall,其中有一行標記爲'row1',值爲'foo'和'bar'。我想只選擇dfall的列,其中'row1'的值爲'foo'。Python pandas:選擇列滿足某個條件的列

換句話說:

dfall= pd.DataFrame([['bar','foo'],['bla','bli']], columns=['col1','col2'], index=['row1','row2']) 

我想作爲導致列「col2'containing:['foo','bli']

我想:

dfall[dfall.loc['row1'].isin(['foo'])] 

我得到的錯誤

IndexingError: Unalignable boolean Series key provided 

任何人都可以幫助我執行命令嗎?提前致謝!

回答

1

您可以比較DF對標值,然後使用anyaxis=0,並通過這個布爾面具ix

In [324]: 
df.ix[:,(df == 'foo').any(axis=0)] 

Out[324]: 
    col2 
row1 foo 
row2 bli 

突破上述下降:

In [325]: 
df == 'foo' 

Out[325]: 
     col1 col2 
row1 False True 
row2 False False 

In [326]: 
(df == 'foo').any(axis=0) 

Out[326]: 
col1 False 
col2  True 
dtype: bool 
+0

此答案假定所有列都包含字符串。對於問題中給出的示例數據框,情況確實如此,但這顯然是佔位符。如果有數字列,''df =='foo'''將會失敗並出現''TypeError''。 – Schmuddi

+0

@Schmuddi我只能回答說明的內容,除非OP完全描述問題域,那麼這個答案滿足當前問題 – EdChum

+0

非常感謝!爲了使它具體行,我做了:df.ix [:,(df.loc ['row1'] =='foo')] – Fringant

0

使用EdChum的答案,使其具體行我做了: df.ix [:,(df.loc ['row1'] =='foo')]

相關問題