Python 根据字符串索引向 DataFrame 添加行

Python adding rows to DataFrame based on string indexing

我正在使用一个每天更新的文本文件,我想从字符串中提取值并将它们附加到 DataFrame。文本文件在结构上没有变化(至少大部分),只是更新了值,所以我编写了一些代码来提取列表中关键字前面的值。

为了让我的生活更轻松,我尝试构建一个 for 循环以尽可能实现自动化,但令人沮丧的是,我一直坚持将我获取的值附加到我的 DataFrame。我看过的所有教程都在处理 for 循环中的范围。

empty_df = pd.DataFrame(columns = ["date","builders","miners","roofers"])

text = "On 10 May 2022, there were 400 builders living in Rome, there were also no miners and approximately 70 roofers"
text = text.split()
profession = ["builders","miners","roofers"]

for i in text:
    if i in profession:
       print(text[text.index(i) - 1] + " " + i)

400 builders
no miners
70 roofers

我尝试附加使用:

for i in text:
    if i in profession:
       empty_df.append(text[text.index(i) - 1] + " " + i)

但这不起作用,我真的不确定如何附加多个计算变量。

所以我想知道的是:

  1. 如何将结果值附加到正确列中的空数据框。
  2. 如何将 'no' 或 'none' 转换为零。
  3. 每次更新时如何合并日期?

谢谢

1)如何将结果值附加到正确列中的空数据框。

我认为你之前需要做一个预处理,当你检测到一个关键字(builders)时,你应该在句子中迭代,你把前后的词(用''分割)。现在你尝试将它转换为浮点数之前和之后的单词如果它有效你将结果存储在列表列表中:['builders',400]并且你已经搜索了所有你能够添加行的所有内容资讯

2) 如何将 'no' 或 'none' 转换为零。

用我的方法你不需要,如果你能在float中转换之前或之后的词,那么它应该是0

3) 如何在每次更新时合并日期?

https://theautomatic.net/2018/12/18/2-packages-for-extracting-dates-from-a-string-of-text-in-python/

如果您只想要一个即插即用的解决方案,这将帮助您到达目的地:

from dateutil import parser
import numpy as np

empty_df = pd.DataFrame(columns = ["builders","miners","roofers","date"])
text = "On 10 May 2022, there were 400 builders living in Rome, there were also no miners and approximately 70 roofers"
date = parser.parse(text.split(',')[0]).strftime('%d %B %Y')

foo = text.split()
profession = ["builders","miners","roofers"]

total_no = []
for i in foo:
    if i in profession:
       total_no.append(foo[foo.index(i) - 1])

empty_df.loc[len(empty_df)] = total_no + [date]

empty_df.replace('no', np.nan)

输出:

    builders    miners  roofers date
0   400         NaN     70      10 May 2022