Trying to return number of items in a list as a column in a dataframe
<p>I have a pandas dataframe, 'df', like the following:</p>

<pre><code>      name    things_in_bag

0     Don     [orange, pear, apple]
1     Tommy   [banana, pear, apple, watermelon]
2     Larry   [cucumber]
.
.
1084  Jen     [pear, baseball]
</code></pre>

<p>I want to add a column called 'number_things' that totals the things in the bag.</p>

<p>I know I can use len() to get the count of the items in those arrays, however, the problem is accessing the index.  So the number of items in the first row is len(df.loc[0, 'things_in_bag']).</p>

<p>But how do I populate all 1084 rows of the new column?</p>

<p>you can use apply and look at the len of the list such as</p>

<pre><code>df['things_in_bag'].apply(len)
</code></pre>

<p>if you want to populate a new columns with that data you can then do</p>

<pre><code>df['newcol'] = df['things_in_bag'].apply(len)
</code></pre>

python pandas dataframe