簡體   English   中英

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. 我怎樣才能將“否”或“無”轉換為零。
  3. 每次更新時,我怎樣才能合並日期?

謝謝

如果您只想要一個即插即用的解決方案,這將使您到達您需要去的地方:

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

1)如何將結果值附加到正確列中的空數據框中。

我認為您需要在之前進行預處理,當您檢測到關鍵字(構建器)時,您應該在句子中進行迭代,您在之前和之后取詞(用''分割)。 現在,您嘗試將其轉換為浮點數之前和之后的單詞,如果它有效,您將結果存儲在列表列表中:['builders',400] 並且您已經搜索了可以添加所有信息的行的所有內容

2)如何將“否”或“無”轉換為零。

使用我的方法,如果您能夠在浮點數中轉換之前或之后的單詞,則不需要,那么它應該是 0

3)我如何在每次更新時也包含日期?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM