Sort lists in a Pandas Dataframe column
<p>I have a Dataframe column which is a collection of lists</p>

<pre><code>    a
['a', 'b']
['b', 'a']
['a', 'c']
['c', 'a']
</code></pre>

<p>I would like to use this list to group by its unique values (['a', 'b'] &amp; ['a', 'c']). However, this generates an error </p>

<pre><code>TypeError: unhashable type: 'list'
</code></pre>

<p>Is there any way around this. Ideally I would like to sort the values in place and create an additional column of a concatenated string.</p>

<p>You can also sort values by column.</p>

<p>Example:</p>

<pre><code>x = [['a', 'b'], ['b', 'a'], ['a', 'c'], ['c', 'a']]
df = pandas.DataFrame({'a': Series(x)})
df.a.sort_values()

     a
0   [a, b]
2   [a, c]
1   [b, a]
3   [c, a]
</code></pre>

<p>However, for what I understand, you want to sort <code>[b, a]</code> to <code>[a, b]</code>, and <code>[c, a]</code> to <code>[a, c]</code> and then <code>set</code> values in order to get only <code>[a, b][a, c]</code>.</p>

<p>i'd recommend use <code>lambda</code></p>

<p>Try:</p>

<pre><code>result = df.a.sort_values().apply(lambda x: sorted(x))
result = DataFrame(result).reset_index(drop=True)
</code></pre>

<p>It returns:</p>

<pre><code>0    [a, b]
1    [a, c]
2    [a, b]
3    [a, c]
</code></pre>

<p>Then get unique values:</p>

<pre><code>newdf = pandas.DataFrame({'a': Series(list(set(result['a'].apply(tuple))))})
newdf.sort_values(by='a')

     a
0   (a, b)
1   (a, c)
</code></pre>

python pandas