Pandas:获取系列的前 10 个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39867061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: get first 10 elements of a series
提问by chintan s
I have a data frame with a column tfidf_sorted
as follows:
我有一个带有列的数据框,tfidf_sorted
如下所示:
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...
The type(df.tfidf_sorted)
returns pandas.core.series.Series
.
的type(df.tfidf_sorted)
回报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.
tfidf
字典在哪里。
How do I get the first 10 key-value pairs from tfidf_sorted
?
如何从 中获取前 10 个键值对tfidf_sorted
?
采纳答案by jezrael
IIUC you can use:
您可以使用 IIUC:
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 need top 10 per row add [:10]
:
或者,如果需要每行前 10 个添加[:10]
:
df['tfidf_sorted'] = df['tfidf'].apply(lambda y: (sorted(y.items(), key=lambda x: x[1], reverse=True))[:10])