python - 仅当行值满足 Python 中的特定条件时,才在 Pandas 数据框中选择列名
问题描述
我想从我的数据集的每一行中获取值为 0.6 或更大的那些列的名称。
数据集的形式是我有一个句子,对于每个句子,我都有那个句子中每个相关单词的 tf-idf 值。
Sample dataset:
heel syrup word3 word4 word5
What is a better exercise? 0 0 0 0 0.34
how many days hv to take syrup 0 0.95 0 0 0
Can I take this solution ? 0 0 0 0 0.23
数据集非常庞大,大约有 10K 行是句子,5K 列是单词。从这里我想创建一个新列,并为每个句子保留 tf-idf 值大于 0.6 的单词。实现的代码是:
dataset = pd.read_csv(r'Desktop/tfidf_val.csv')
dataset.apply(lambda x: x.index[x.astype(bool)].tolist(), 1)
但我收到内存错误,也不确定这段代码是否正确。知道如何解决这个问题,或者代码是否有问题
解决方案
您可以使用矩阵乘法来快速连接单词:
thresh= 0.2 # change this to 0.6 as asked
(df>0.2)@(df.columns+',')
输出:
What is a better exercise? word5,
how many days hv to take syrup syrup,
Can I take this solution ? word5,
dtype: object
或者,如果您想要列表(如您的代码中所示):
df.apply(lambda x: list(x.index[x>thresh]), axis=1)
输出:
What is a better exercise? [word5]
how many days hv to take syrup [syrup]
Can I take this solution ? [word5]
dtype: object
推荐阅读
- c# - 未在 C# 中定义或导入预定义类型“System.String”
- java - 手动运行测试时找不到 GradleWorkerMain
- reactjs - 反应路由器:位置“/”无法识别?
- angular - 遍历地图
两次,一次用于键,一次用于数组 - javascript - 如何使用 URL 哈希实现同位素过滤?
- c++ - Visual Studio 错误:在使用向量实现 QuickSort 时“无法在开始之前寻找向量迭代器”
- java - 如何在 Mendix 中将普通 Java 项目转换为 Maven 项目?
- arduino - Arduino Zero 上 I2C 引脚的正确配置(通常为保留引脚)
- telegram - Telegram CPP/Mt4 如何在仅限邀请的频道中收听消息,必须分发应用程序
- javascript - 如何在 JS 中使用 try、catch、.then 链接和异步等待来解决承诺?