python - 如何使用熊猫检查csv文件中的特定字符
问题描述
我已经将一个 CSV 文件读入 pandas 数据框,并试图找到所有包含我正在寻找的单词的句子,并且当找到其中任何一个时,使用主 CSV 中的原始索引而不是新索引来打印它。这是我正在尝试的代码,但由于某种原因它给了我一个错误
lookfor = '[' + re.escape(",?!.:;'؛؛؟'-)(؛،؛«/") + ']'
tdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(tdata.count(' ') == 0)
tdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)
newdata=tdata[tdata['sentences'].str.isin(lookfor)]
print (newdata)
#a sample set
-----------------------------
#hi, how are; you
#im good thanks
#How ? Is live.
#good, what about ) you/
#my name is alex
#hello, alex how are you !
#im good!
#great news
#thanks!
-----------------------------
它返回此错误
newdata=tdata[tdata['sentences'].str.isin(pat)]
AttributeError: 'StringMethods' object has no attribute 'isin'
输入数据看起来像
我期待的输出是
解决方案
您可能想要“包含”方法,例如
df = tdata[tdata.sentences.str.contains(pat, regex=True, na=False)]
完整的代码应该是这样的;
lookfor = '[' + re.escape(",?!.:;'؛؛؟'-)(؛،؛«/") + ']'
tdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(tdata.count(' ') == 0)
tdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)
tdata['row_index'] = 1
tdata['row_index'] = tdata['row_index'].cumsum()
filtered = tdata[tdata.sentences.str.contains(lookfor, regex=True, na=False)]
filtered.to_csv('./my_path.csv', index=False)
推荐阅读
- javascript - 在带有装饰器和 HOC 的类组件中使用 react-i18next
- kotlin - 复杂层次结构的多态 kotlinx 序列化
- android - FLAG_INSISTENT 当另一个通知弹出时停止重复通知声音
- javascript - 有两个对象的数组,在这些数组中,如果 ID 相同,我想匹配 ID 我需要新的数组,其中包含相同 ID 的组合信息
- amazon-web-services - AWS IAM 理解问题
- python - 在 django 会话中正确存储和访问用户
- c# - 加载仅在代码执行结束时出现
- image - PNG图像(在锚中)未显示透明背景
- json - 如何使用颤振获得 wordpress 帖子
- azure - Azure - 通过 HTTP API 创建数据库(使用 Secret) - 403 错误