熊猫数据框过滤器不起作用,但str.match()起作用

时间:2020-05-24 11:59:13

标签: python pandas dataframe

我有一个熊猫数据框words_df,其中包含一些英语单词。

只有一列名为word的列包含英语单词。

words_df.tail()

enter image description here

words_df.dtypes

enter image description here

我想过滤出包含 zythum

一词的行

使用熊猫系列str.match()给了我预期的输出:

words_df[words_df.word.str.match('zythum')]

我知道str.match()并不是正确的执行方式,它还会返回包含诸如 zythums 之类的其他单词的行。

enter image description here

但是,对Pandas Dataframe使用以下操作会返回一个空的Dataframe

words_df[words_df['word'] == 'zythum']

enter image description here

我想知道为什么会这样吗?

编辑1: 我还将附加数据源和用于导入数据的代码。

数据源(我使用了“ csv.zip中的单词列表” ):

https://www.bragitoff.com/2016/03/english-dictionary-in-csv-format/

数据框导入代码:

import pandas as pd
import glob as glob
import os as os
import csv

path = r'data/words/' # use your path
all_files = glob.glob(path + "*.csv")

li = []

for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=None, names = ['word'], engine='python', quoting=csv.QUOTE_NONE)
    li.append(df)

words_df = pd.concat(li, axis=0, ignore_index=True)

编辑2:

这是我的代码块,带有更简单的导入代码,但面临相同的问题。 (使用上述链接中的 Zword.csv 文件) enter image description here

4 个答案:

答案 0 :(得分:1)

IIUC:print(os.linesep) tag=input("your username here : ") instagram ='https://www.instagram.com/' x=requests.get(instagram+tag) if x.status_code == 200: print("Instagram found: "+tag) else: print("not found") 无法正常工作。

尝试,删除数据框中字符串周围的空格:

df1[df1['word'] == 'zythum']

答案 1 :(得分:1)

您导入的列表与您要查找的字符串不完全匹配。 csv文件中的单词后面有一个空格。

您应该能够使用str.strip去除空白。例如:

import pandas as pd
myDF = pd.read_csv('Zword.csv')
myDF[myDF['z '] == 'zythum '] # This has the whitespace
myDF['z '] = myDF['z '].map(str.strip)
myDF[myDF['z '] == 'zythum'] # mapped the whitespace away

答案 2 :(得分:0)

您需要将整列转换为str类型:

    words_df['word'] = words_df['word'].astype(str)

这应该适合您的情况。

答案 3 :(得分:0)

在这里,您可以使用它来完成工作。根据需要更改参数。

import glob as glob
import os as os
import csv

def match(dataframe):
    l = []
    for i in dataframe:
        l.append('zythum' in i)
    data = pd.DataFrame(l)
    data.columns = ['word']
    return data

path = r'Word lists in csv/' # use your path
files = os.listdir(path)
li = []
for filename in files:
    df = pd.read_csv(path + filename, index_col=None, header=None, names = ['word'], engine='python', quoting=csv.QUOTE_NONE)
    li.append(df)
words_df = pd.concat(li, axis=0, ignore_index=True)

words_df[match(words_df['word'])].dropna()```