Pandas groupby over list
<p>I have a pandas data frame in the following format:</p>

<pre><code>Arrival Departure Park Station Count 
      8        10    5   [1,2]     1
      5        12    6   [3,4]     1
      8        10    5   [1,2]     1
</code></pre>

<p>I want to groupby this data frame by arrival, departure, park and station but since station is a list, I am getting an error. The output should look like:</p>

<pre><code>    Arrival Departure Park Station Count 
        8        10    5   [1,2]     2
        5        12    6   [3,4]     1
</code></pre>

<p>Could you please let me know if there is any way to solve this issue?         </p>

<p>The problem is that a <a href="http://stackoverflow.com/questions/19371358/python-typeerror-unhashable-type-list">Python <code>list</code> is a mutable type, and hence unhashable</a>. In the place you'd put in the <code>groupby</code> criterion <code>df.Station</code>, put instead <code>df.Station.apply(tuple)</code>. This will transform the lists into tuples, which are hashable (and immutable).</p>

<p>For example:</p>

<pre><code>In [66]: df = pd.DataFrame({'Arrival': [8, 5, 4], 'Station': [[1, 2], [3, 4], [1, 2]]})

In [67]: df.groupby([df.Arrival, df.Station.apply(tuple)]).Arrival.sum()
Out[67]: 
Arrival  Station
4        (1, 2)     4
5        (3, 4)     5
8        (1, 2)     8
Name: Arrival, dtype: int64
</code></pre>

<p>Conversely,</p>

<pre><code>df.groupby([df.Arrival, df.Station]).Arrival.sum()
</code></pre>

<p>won't work.</p>

python list pandas dataframe