pandas groupby a list of strings
<p>Imagine if you have a list of strings and a pandas dataframe with a column <code>Foo</code> that has words which may contain those strings:</p>

<p><code>
my_list = ['A', 'B', 'C']
</code> </p>

<p>df['Foo'] has words that contain 'A' or 'B' or 'C',</p>

<p>you can extract the ones that contain by <code>df.Foo.str.contains(my_list[0])</code> etc., but can you group by the rows that match the list? So the groupby would be by contains 'A' or 'B' or 'C'</p>

<p>Yes, you can do this by passing a function to groupby()</p>

<pre><code>data = {'Foo': {0: 'apple',
  1: 'body',
  2: 'animal',
  3: 'cot',
  4: 'cord',
  5: 'bed',
  6: 'ant'}}

df = pd.DataFrame(data)
print (df)

      Foo
0   apple
1    body
2  animal
3     cot
4    cord
5     bed
6     ant
</code></pre>

<p>get_grp() will be called for each value in df['Foo']. Note: x is only the index of df so we have to pass some additional things</p>

<pre><code>def get_grp(x, df, col_name, my_list):
    for c in my_list: 
        if c in df[col_name][x]:
            return c


 my_list = ['a', 'b', 'c']
 g = df.groupby(lambda x : get_grp(x, df, 'Foo', my_list))
 print (type(g))
 print (g.count())

&lt;class 'pandas.core.groupby.DataFrameGroupBy'&gt;
   Foo
a    3
b    2
c    2
</code></pre>

<p>Note: get_grp() only returns one item of my_list.  So 'Ball' would only fall into one grouping and it would be 'a' because its the first item in my_list that we check </p>

python pandas data-analysis