1

我正在尝试从从 .csv 读取的以下 DataFrame 中删除停用词。它基本上是一长串二元组及其在洗发水标签数据集中出现的频率。

目标是在“word1”或“word2”列中出现停用词时删除整行。

                        word1                      word2  frequency
0                       nicht                         in       3069
1                        wenn                        sie       2729
2                         von                    kindern       2108
3                         die                      hände       2094
4                        darf                      nicht       2091
5                       hände                        von       2091
6                      citric                       acid       2088
7                     kindern                   gelangen       2082
8                         sie                      einen       2053
9                         mit                        den       2023
10                       eine                   reaktion       1976

然而,到目前为止,当它与来自 nltk 的德语停用词匹配时,我什至没有设法删除仅基于列“word1”的行。

我使用的代码是基于先前在此处回答的问题。

import pandas as pd
from nltk.corpus import stopwords

stop = stopwords.words('german')

df = pd.read_table("myfile.csv", sep=";")
df.columns = ["word1","word2","frequency"]

df["word1"] = df["word1"].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))

print(df) 

我得到的错误是: AttributeError: 'list' object has no attribute 'split'

我完全理解我在这里有错,因为我不理解被调用的函数。我正在尝试在一边做课程的同时加深对 pandas 和 nltk 的理解,但这并没有真正去任何地方:)

清除 DataFrame 中的停用词后,目标是将其写入新的 CSV。但那是为了以后的阶段。

编辑:标题更改以进行澄清

4

2 回答 2

0

您可以为此目的使用列表推导。在这里,创建了一个新列temp。如果word1word2中的任何一个处于stop状态,则temp的值为False删除temp值为False的那些行。最后,删除该临时列并写入新的 csv 文件。希望这可以帮助。

import pandas as pd
from nltk.corpus import stopwords

stop = stopwords.words('english')
df = pd.read_csv("myfile.csv", sep=";")


df["temp"] = [True  if row.word1 not in stop and row.word2 not in stop else False for index, row in df.iterrows()]
df = df[df.temp == True]
df.drop('temp', axis=1, inplace=True)

df.to_csv("myfile_out.csv", sep=';') 
于 2018-06-21T06:49:55.563 回答
-1

apply -function不会删除任何行。它只是将一个函数映射到 Series df["word1"]的每个元素上。此外,您在“word1”列中的条目似乎是list类型而不是string类型。

但是,如果df是一个 pandas DataFrame,其中包含一个带有字符串的列“word1”,那么就这样做

df = df[~df["word1"].isin(stop)]

...然后您从 df 中删除所有条目,其中“word1”处于停止状态。这里~是否定运算符,所以它的意思是not。some_series.isin (some_iterable)方法返回一个与some_series具有相同索引的Series ,其中每个条目都是一个布尔值,表示 some_series 中的相应条目是否包含在some_iterable中。

通常,您可以从 DataFrame 中选择切片

df[Series of booleans]

其中“系列”是指熊猫系列。由于 pandas Series 与比较运算符一起使用,您可以执行以下操作

df[df["frequency"] > 2060]

它返回一个 DataFrame 只包含频率值高于 2060 的行。

编辑:我不确定是否反对来自您,但如果此处提供的代码不起作用,您应该显示几行 .csv 文件,因为仅从您的代码我们无法知道您的 DataFrame 的外观完全一样。

干杯,西拉斯

于 2018-06-20T22:21:51.810 回答