Pandas: get first 10 elements of a series
<p>I have a data frame with a column <code>tfidf_sorted</code> as follows:</p>

<pre><code>   tfidf_sorted

0  [(morrell, 45.9736796), (football, 25.58352014...
1  [(melatonin, 48.0010051405), (lewy, 27.5842077...
2  [(blues, 36.5746634797), (harpdog, 20.58669641...
3  [(lem, 35.1570832476), (rottensteiner, 30.8800...
4  [(genka, 51.4667410433), (legendaarne, 30.8800...
</code></pre>

<p>The <code>type(df.tfidf_sorted)</code> returns <code>pandas.core.series.Series</code>.</p>

<p>This column was created as follows:</p>

<pre><code>df['tfidf_sorted'] = df['tfidf'].apply(lambda y: sorted(y.items(), key=lambda x: x[1], reverse=True))
</code></pre>

<p>where <code>tfidf</code> is a dictionary.</p>

<p>How do I get the first 10 key-value pairs from <code>tfidf_sorted</code>?</p>

<p>IIUC you can use:</p>

<pre><code>from itertools import chain 

#flat nested lists
a = list(chain.from_iterable(df['tfidf_sorted']))
#sorting
a.sort(key=lambda x: x[1], reverse=True)
#get 10 top
print (a[:10])
</code></pre>

<p>Or if need top 10 per row add <code>[:10]</code>:</p>

<pre><code>df['tfidf_sorted'] = df['tfidf'].apply(lambda y: (sorted(y.items(), key=lambda x: x[1], reverse=True))[:10])
</code></pre>

python list python-2.7 pandas indexing