Pandas: Get The First 10 Elements Of The Series

I have a data frame with a tfidf_sorted column as follows:

  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... 

type(df.tfidf_sorted) returns pandas.core.series.Series .

This column was created as follows:

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

where tfidf is a dictionary.

How to get the first 10 key-value pairs from tfidf_sorted ?

+5
source share
1 answer

IIUC you can use:

 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]) 

Or, if you need the top 10 in the line, add [:10] :

 df['tfidf_sorted'] = df['tfidf'].apply(lambda y: (sorted(y.items(), key=lambda x: x[1], reverse=True))[:10]) 
+2
source

Source: https://habr.com/ru/post/1257719/


All Articles