Skip to main content
 首页 » 编程设计

python之在包含来自 Pandas 中另一个数据帧的单词的数据帧中检索行

2024年09月07日7soundcode

我正在尝试检索包含来自另一个数据帧的单词的数据帧中的行。在下面的链接中附上了 .csv 文件。我已经试过了,但它只给了我一个字:

import numpy as np 
import pandas as pd 
 
sentiment_words = pd.read_csv('sentiment_words.csv') 
tokens = pd.read_csv('tokens.csv') 
 
tokens[tokens['token'].isin(sentiment_words['sentiment_words'])] 
 
Out[201]: 
               Class8    Class9         token   
    4156     0.004092  0.014243      abnormal   
    4421     0.000000  0.013170       abolish   
    4500     0.042788  0.062791    abominable  

我想要的输出与下面类似,只是我想用 sentiment_words 数据框中的单词替换“not”

tokens[tokens['token'].str.contains("not")] 
 
           Class8    Class9                  token   
210      0.000000  0.000000        aaand annnother   
396      0.000000  0.006581               aang not   
459      0.000000  0.000000            aardman not   
624      0.000000  0.000000              aaron not   
1147     0.000000  0.007496      abandoned another   
2301     0.000000  0.000000           abducted not   

情感词.csv:https://www.dropbox.com/s/y2ya5lr4wgl940y/sentiment_words.csv?dl=0 token .csv:https://www.dropbox.com/s/wdvprygmnm13lwd/tokens.csv?dl=0

已经花了几个小时在线搜索,但到目前为止没有任何方法,因此非常感谢您的帮助。谢谢!

请您参考如下方法:

将 nrows 传递给 pd.read_csv() 我能够使用您的 dl 链接制作示例代码。这是你想要的吗?

import pandas as pd 
 
url1 = 'https://www.dropbox.com/s/y2ya5lr4wgl940y/sentiment_words.csv?raw=1' 
url2 = 'https://www.dropbox.com/s/wdvprygmnm13lwd/tokens.csv?raw=1' 
 
sentiment_words = pd.read_csv(url1) 
tokens = pd.read_csv(url2, nrows=1000) # Limit rows read to 1000 
 
# Create regex pattern 
# We need to replace * and + as they will not work without escape in regex 
pat = '|'.join(sentiment_words['sentiment_words'].str.replace('*','\*') 
                                                 .str.replace('+','\+')) 
 
# Create mask and apply overwriting old values 
m2 = tokens['token'].str.contains(pat, regex=True) 
tokens = tokens.loc[m2] 
 
tokens