Append row with counts in PANDAS
<p>I have a data frame with categorical data structured in the following way:</p>

<pre><code>index    A    B    C    D
ind1     0    0    1    2
ind2     1    0    2    0
ind3     2    1    0    0
</code></pre>

<p>I would like to append a row which sums only the instances of <code>"1"</code>. The desired result would look like:</p>

<pre><code>index    A    B    C    D
ind1     0    0    1    2
ind2     1    0    2    0
ind3     2    1    0    0
count1   1    1    1    0
</code></pre>

<p>I have imported the table such that all characters are strings and have tried the following:</p>

<pre><code>dataframe = dataframe.append(dataframe.applymap(lambda x: str.count(x, "1"))
</code></pre>

<p>However this results in numerous additional rows without meaning. Any help is much appreciated!!</p>

<p>You can sum boolean mask <code>df == 1</code>:</p>

<pre><code>print (df == 1)
           A      B      C      D
index                            
ind1   False  False   True  False
ind2    True  False  False  False
ind3   False   True  False  False


df.loc['count1'] = (df == 1).sum()

print (df)
        A  B  C  D
index             
ind1    0  0  1  2
ind2    1  0  2  0
ind3    2  1  0  0
count1  1  1  1  0
</code></pre>

python pandas sum append condition