Python pandas: Select columns where a specific row satisfies a condition
<p>I have a dataframe dfall where there is a row labeled 'row1' with values 'foo' and 'bar'. I want to select only columns of dfall where 'row1' has the value 'foo'.</p>

<p>In other words:</p>

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

<p>I want as result the column 'col2'containing: <code>['foo','bli']</code></p>

<p>I tried:</p>

<pre><code>dfall[dfall.loc['row1'].isin(['foo'])]
</code></pre>

<p>I get the error </p>

<pre><code>IndexingError: Unalignable boolean Series key provided
</code></pre>

<p>Can anybody help me with the command? Thanks in advance!</p>

<p>You can compare your df against the scalar value, and then use <code>any</code> with <code>axis=0</code> and pass this boolean mask to <code>ix</code>:</p>

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

Out[324]:
     col2
row1  foo
row2  bli
</code></pre>

<p>breaking the above down:</p>

<pre><code>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
</code></pre>

python pandas select