【问题标题】:Cumulative Unique words in huge dataframe巨大数据框中的累积唯一词
【发布时间】:2019-06-20 02:16:37
【问题描述】:

如何从每个超过 500 个单词的数据框列中获取累积的唯一单词。数据框有 ~300,000 行

我在 A 列包含文本数据的数据框中读取了 csv 文件。 我尝试通过遍历 A 列并从 A 列中获取唯一单词作为集合并在 B 列和 C 列中添加唯一单词来创建几列(B 和 C)

随后,我通过从前一行(集合)中获取 A 列和 B 列(联合)来获取唯一的单词

这适用于少量行。但是一旦行数超过 10,000 行,性能就会下降,内核最终会死掉

对于巨大的数据框有没有更好的方法?

尝试使用唯一的单词和计数创建单独的数据框,但仍然有问题

示例代码:

for index, row in DF.iterrows():
      if index = 0:
          result = set(row['Column A'].lower().split()
          DF.at[index, 'Column B'] = result
      else:
          result = set(row['Column A'].lower().split()
          DF.at[index, 'Cloumn B'] = result.union(DF.loc[index -1, 
                                                'Column B'])
DF['Column C'] = DF['Column B'].apply(len)

【问题讨论】:

  • 贴出你的代码,不要描述它。同时发布minimal, complete and verifiable example
  • 抱歉,贴出代码
  • 所以您只想要数据框中的“A Column”的所有唯一值?
  • A 列的累积唯一值,A 列的累积唯一字数

标签: python pandas dataframe nlp


【解决方案1】:

利用字典键的唯一性来累积单词。

我创建了一个字典cumulative_words,我想在其中逐行存储唯一单词,方法是使用具有给定行句子中唯一单词的键的字典对其进行更新。

代码:

cumulative_words = {}

def cumulate(x):
    cumulative_words.update(dict.fromkeys(set(x.lower().split())))
    return list(cumulative_words.keys())

df["Column B"] = df["Column A"].apply(cumulate)
df["Column C"] = df["Column B"].apply(len)

更新:

鉴于您说这段代码在大约 200k 行时仍然存在内存问题, 我会尝试一些非常简单的东西来理解更多:

  1. 只需更新累积字典

在数据帧操作之前创建具有唯一词的字典

cumulative_words = {}

for x in df["Column A"].values:
    cumulative_words.update(dict.fromkeys(set(x.lower().split())))

如果这仍然失败,我认为我们必须改变方法

  1. 将字词附加到列表中

这是我认为的关键点,因为它创建了一个包含大约数十亿个单词的列表

cumulative_words = {}
cumulative_column = []

for x in df["Column A"].values:
    cumulative_words.update(dict.fromkeys(set(x.lower().split())))
    cumulative_column.append(cumulative_words.keys())
  1. 将创建的列表分配给 B 列并计数
df["Column B"] = cumulative_column
df["Column C"] = df["Column B"].apply(len)

可能要存储的单词太多,无法创建数据框,或者我不知道该怎么做。告诉我

【讨论】:

  • Lante 的解决方案比我之前的尝试提供了更好的结果。不完美,因为它仍然会在 ~ 200K 行时中断
  • 很高兴你欣赏我的选择,但我很好奇,如果它坏了会发生什么?
  • 在 Jupyter notebook 中运行时内核死机或内存错误
  • 我添加了一些我会做的事情
【解决方案2】:

您可以使用 CountVectorizer 并在之后进行累计。

了解更多关于 CountVectorizer 的信息:https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html 和 pandas 的累计和:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.cumsum.html

【讨论】:

  • CountVectorizer 仅在我必须获取每列的唯一字数时才有效。我需要获取 B 列中所有先前行的累积单词。但是当我使用单词时,获取总和相对容易
  • 你能提供一个数据样本来测试你的代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-19
  • 2014-01-03
  • 2018-12-29
  • 1970-01-01
  • 2021-03-13
相关资源
最近更新 更多