python - Pandas :获取系列的前 10 个元素

标签 python list python-2.7 pandas indexing

我有一个包含列 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...

type(df.tfidf_sorted) 返回 pandas.core.series.Series

此专栏创建如下:

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

其中 tfidf 是字典。

如何从 tfidf_sorted 中获取前 10 个键值对?

最佳答案

您可以使用 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])

或者如果需要每行前 10 个,添加 [:10]:

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

关于python - Pandas :获取系列的前 10 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867061/

相关文章:

python - 我可以对 python 中的列表执行减号或连接操作,包括重复条目

c# - c# winForms 列表数组的奇怪结果

python - 调试 ansible 跟踪以查找 python 云堆栈模块中可能存在的错误

python - Pyinstaller 在使用 matplotlib 时显示一些错误

python - 如何从 PostgreSQL 查询流式传输超出内存容量的数据到 Parquet 文件?

Python函数在不修改输入列表的情况下返回一个新列表

python - 无法在 Django Rest Framework View 集中的模型方法中显示带注释的查询集

python - Pandas df.plot 子图上的多个传说?

python - 常量类实例是 PEP8 命名约定的异常(exception)吗?

python - MessagePack 和消息帧