Update Pandas Cells based on Column Values and Other Columns
<p>I am looking to update many columns based on the values in one column; this is easy with a loop but takes far too long for my application when there are many columns and many rows. What is the most elegant way to get the desired counts for each letter?</p>

<p>Desired Output:</p>

<pre><code>   Things         count_A     count_B    count_C     count_D
['A','B','C']         1            1         1          0
['A','A','A']         3            0         0          0
['B','A']             1            1         0          0
['D','D']             0            0         0          2
</code></pre>

<p><strong><em>option 1</em></strong><br>
<code>apply</code> + <code>value_counts</code></p>

<pre><code>s = pd.Series([list('ABC'), list('AAA'), list('BA'), list('DD')], name='Things')

pd.concat([s, s.apply(lambda x: pd.Series(x).value_counts()).fillna(0)], axis=1)
</code></pre>

<p><a href="https://i.stack.imgur.com/isZYF.png" rel="nofollow"><img src="https://i.stack.imgur.com/isZYF.png" alt="enter image description here"></a></p>

<p><strong><em>option 2</em></strong><br>
use <code>pd.DataFrame(s.tolist())</code> + <code>stack</code> / <code>groupby</code> / <code>unstack</code></p>

<pre><code>pd.concat([s,
           pd.DataFrame(s.tolist()).stack() \
             .groupby(level=0).value_counts() \
             .unstack(fill_value=0)],
          axis=1)
</code></pre>

python pandas apply