Python Pandas - Lambda 应用保持初始格式

标签 python pandas

我想改造这个系列

from nltk import word_tokenize, pos_tag
from nltk.corpus import stopwords
stop_words = set(stopwords.words("english"))
df = pd.Series([["comic of book", "horror of movie"], ["dark", "dark french"]])
>> 0  [comic of book, horror of movie]
>> 1  [dark, dark french]

通过删除停用词并仅保留名词(nltk中的NN)。我认为 apply 函数是最好的解决方案,但是将其直接应用于这些文本会导致信息丢失。我明白了

df.apply(lambda x: [wrd for ing in x for wrd in word_tokenize(ing) if wrd not in stop_words])
0    [comic, book, horror, movie]
1            [dark, dark, french]

而不是

0    [comic book, horror movie]
1            [dark, dark french]

我错过了for循环中的一些内容,它用唯一的单词分隔了每个词袋(也许apply > 这里不好)

最佳答案

def rmsw(y):
    return ' '.join(set(y.split()) - stop_words)

pd.Series([[rmsw(y) for y in x] for x in df], df.index)

0    [comic book, horror movie]
1           [dark, dark french]
dtype: object
<小时/>

维持秩序和频率

def rmsw(y):
    return ' '.join([w for w in y.split() if w not in stop_words])

pd.Series([[rmsw(y) for y in x] for x in df], df.index)

关于Python Pandas - Lambda 应用保持初始格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51062770/

相关文章:

python - 将距离矩阵转换为 newick 字符串格式的系统发育树

Python dataframe 将点击路径行转为列

python-3.x - 30 天滚动窗口中的行数

python - np.where 与日期时间产生 Unix 时间戳

python / Pandas : Convert multiple CSV files to have union and ordered header and fill the missing data

python - 在 Pandas 中移动 Groupby

python - 使用 Pandas 将整个数据框从小写转换为大写

sum() 函数的 Python 代码错误——语法在一个平台上有效,在另一个平台上无效

python - 当我更改 DataFrame 的索引时,使用 pandas 进行绘图似乎效果不佳

python 2.7 : remove a key from a dictionary by part of key