如何使用正则表达式在pandas数据框架列中查找值



我有一个PDF文档,在文档中的表格中报告了一个州各县的COVID-19数字。我正在使用camelot将表读入pandas数据框架,并根据第一列中的值(国家名称)提取各行中的值。为此,我使用如下所述的布尔索引:如何使用pandas对匹配给定条件的列中的值求和?

我正在使用提取的数据报告本组织感兴趣的报告中列出的一个县子集的COVID-19统计数据。我还提取了该州的总数,但PDF的生产者不能决定是否要将这一行数据称为"gesamt";("Total")或"Gesamtergebnis"("总result"。在camelot从PDF中提取表之后,我正在使用的数据框架如下所示:

0        1       2        3
...
9        A County   13.789   (+22)  1.566,0
10      My County   16.581   (+45)  3.040,0
11   Their County    7.445   (+15)  2.821,6
... 
55         Gesamt  304.950  (+820)  2.747,2

下面的代码可以工作,如果他们使用"Gesamt."我想写的是,如果他们使用"Gesamtergebnis",它也会起作用。我不能完全依赖("gesamt")。或"Gesamtergebnis")总是在同一行。

# Open LGA reports for yesterday and the day before
# TO DO: Sometimes the LGA report is named COVID_Lagebericht_LGA_yymmdd.pdf or it ends in _01
#        Add in a try/else statement to compensate for this
rptyes = f'Reports_LGA/{yday_yymmdd}_COVID_Tagesbericht_LGA.pdf'
rptdbf = f'Reports_LGA/{daybef_yymmdd}_COVID_Tagesbericht_LGA.pdf'
# Read the LGA reports into dataframes.
dfyes = camelot.read_pdf(rptyes, pages='2', flavor='stream')
dfdbf = camelot.read_pdf(rptdbf, pages='2', flavor='stream')
# Extract the statewide 7-D-I
# TO DO: Sometimes the last line says "Gesamt", sometimes "Gesamtergebnis" or something else.
#        Add in some sort of error checking or try/else statement or regular expression to compensate
landindexyes = lambda land: dfyes[0].df.loc[dfyes[0].df[0] == land].index[0]
landindexdbf = lambda land: dfdbf[0].df.loc[dfdbf[0].df[0] == land].index[0]
land = 'Gesamt'
bwname = 'Baden-Württemberg'
bwcases = int(dfyes[0].df.loc[landindexyes(land), 1].replace('.',''))
bwcasesdiff = dfyes[0].df.loc[landindexyes(land), 2]
bwdeaths = int(dfyes[0].df.loc[landindexyes(land), 4].replace('.',''))
bwdeathsdiff = dfyes[0].df.loc[landindexyes(land), 5]
bw7diyes = float(dfyes[0].df.loc[landindexyes(land), 7].replace(',','.'))
bw7didbf = float(dfdbf[0].df.loc[landindexdbf(land), 7].replace(',','.'))
bw7didiff = bw7diyes - bw7didbf
rptrowsbw = [bwname, bwcases, bwcasesdiff, bwdeaths, bwdeathsdiff, bw7diyes, bw7didbf]

如何使用正则表达式匹配"Gesamt"或";Gesamtergebnis"在变量传递到lambda表达式'landindexyes'和'landindexdbf'?

如果正则表达式不适合,我愿意接受其他建议。我认为if/else也可以,但是我不认为那样会很优雅。

不幸的是,我看不到你的数据帧,所以我不能写出100%正确的行。我想让您参考这里的第一个答案:通过在字符串列中查找精确的单词(不组合)来过滤DataFrame。

所以,在你的例子中是这样的:

df[df["column_name"].str.contains(r'(?:s|^)Gesamt(?:s|$)')]]==True 

df[df["column_name"].str.contains(r'(?:s|^)Gesamtergebnis(?:s|$)')]]==True 

如果不确定数据集中的拼写是否正确,可以尝试匹配算法,如Fuzzy Wuzzy: https://www.datacamp.com/community/tutorials/fuzzy-string-python。

编辑(来自评论):RegEx大大降低了代码的速度,所以如果有一个想法来改变所有的"gesamtergebnis"呢?价值观变成了"gesamt";在专栏里?所以,你可以在你的TODO部分使用这样的内容:

df_name['column_name'] = df_name['column_name'].str.replace('Gesamtergebnis','Gesamt')

然后继续你的代码。

最新更新