Method to sort values in row in pandas Series?
<p>Consider the following <code>pandas.Series</code> object:</p>

<pre><code>import pandas as pd

s = pd.Series(["hello there you would like to sort me", "sorted i would like to be", "the yankees played the red sox", "apple apple banana fruit orange cucumber"])
</code></pre>

<p>I would like to sort the values <strong>inside</strong> each row, similar to the following approach:</p>

<pre><code>for row in s.index:
    split_words = s.loc[row].split()
    split_words.sort()
    s.loc[row] = " ".join(split_words)
</code></pre>

<p>I have a huge dataset, however, so vectorization is important, here. How can I use pandas <code>str</code> attribute to accomplish the same, but much quicker?</p>

<p>I've experienced that Python lists perform better in these situations. Applying piRSquared's logic, a list comprehension would be:</p>

<pre><code>[' '.join(sorted(sentence.split())) for sentence in s.tolist()]
</code></pre>

<p>For timings I've used Shakespeare's works from <a href="http://norvig.com/ngrams/" rel="nofollow">Peter Norvig's website</a>.</p>

<pre><code>s = pd.read_table('shakespeare.txt', squeeze=True, header=None)
s = pd.Series(s.tolist()*10)
r1 = s.str.split().apply(sorted).str.join(' ')
r2 = pd.Series([' '.join(sorted(sentence.split())) for sentence in s.tolist()])

r1.equals(r2)
Out: True

%timeit s.str.split().apply(sorted).str.join(' ')
1 loop, best of 3: 2.71 s per loop

%timeit pd.Series([' '.join(sorted(sentence.split())) for sentence in s.tolist()])
1 loop, best of 3: 1.95 s per loop
</code></pre>

python pandas vector