我在文档的表格中有一个报告一个州的县的新冠肺炎数字的PDF文档。我使用camelot将表读入到pandas数据帧中,并根据第一列中的值提取各行中的值。为此,我使用布尔索引,如下所述:How do I sum values in a column that match a given condition using pandas?
我正在使用提取的数据来报告报告中列出的我的组织感兴趣的一些县的新冠肺炎统计数据。我还提取了州的总数,但是PDF的生产者不能决定是否要将该行数据称为"Gesamt“(" total ")或"Gesamtergebnis”("Total 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]如何使用正则表达式来匹配传递给lambda表达式'landindexyes‘和'landindexdbf’的变量中的"Gesamt“或"Gesamtergebnis”?
如果正则表达式不是可行的方法,我愿意接受其他建议。我认为if/else可能会起作用,但我不认为这会很优雅。
发布于 2021-02-13 04:24:04
不幸的是,我看不到你的数据框,所以我不能写100%正确的行。我想在这里向您推荐第一个答案:Filtering DataFrame by finding exact word (not combined) in a column of strings。
所以,在你的例子中是这样的:
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')
然后继续您的代码。
https://stackoverflow.com/questions/66178201
复制相似问题