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>Not sure if you want to sum over the <code>1s</code> or if you want to count the 1s. This assumes that the <code>dtype</code> is not <code>object</code>. If it is only @jezrael's solution will work if you check against <code>'1'</code> rather than <code>1</code>.</p>

<p>To sum over the 1s:</p>

<pre><code>sr = df.where(df == 1, 0).sum()
sr.name = 'count1'
df.append(sr)
</code></pre>

<p>to count over the 1s you can use the approach highlighted <a href="http://stackoverflow.com/a/39559101/1764089">here</a> by @jezrael</p>

<p>In that case the result is the same since you are summing 1s, but if you wanted to do it over 2 then they will give different results.</p>

python pandas sum append condition