【问题标题】:Unable to append multiple data frame with a loop function - Only returns empty Data Frame | Pandas, Python无法使用循环函数附加多个数据框 - 仅返回空数据框 |熊猫,蟒蛇
【发布时间】:2021-11-26 11:17:28
【问题描述】:

我使用以下代码通过网络抓取获取了我的数据:

import requests
import re
import pandas as pd
from urllib.parse import unquote
from json import loads
from bs4 import BeautifulSoup

# Download URL
url = "https://riwayat-file-covid-19-dki-jakarta-jakartagis.hub.arcgis.com/"
req = requests.get(url)

# Get encoded JSON from HTML source
encoded_data = re.search("window\.__SITE=\"(.*)\"", req.text).groups()[0]

# Decode and load as dictionary
json_data = loads(unquote(encoded_data))

# Get the HTML source code for the links
html_src = json_data["site"]["data"]["values"]["layout"]["sections"][1]["rows"][0]["cards"][0]["component"]["settings"]["markdown"]

# Parse it using BeautifulSoup
soup = BeautifulSoup(html_src, 'html.parser')

# Get links
links = soup.find_all('a')

# For each link...
link_list = []
id_list = []
date_list = []
dataframe_csv = []

for link in links:
    if "2021" in link.text:
       link_list.append(link.text+" - "+link.attrs['href'])

link_list.remove("31 Januari 2021 Pukul 10.00 - https://drive.google.com/file/d/1vd1tToQbx3A420KMDA63aKviLjgGPJMd/view?usp=sharing")

for i in link_list:
    id_list.append(i.split("/")[5])
    date_list.append(i.split("/")[0][:-21])
    
for ID in id_list:
    dataframe_csv.append("https://docs.google.com/spreadsheets/d/"+ID+"/export?format=csv")

我想使用循环函数将多个数据帧附加到一个空数据帧“df_total”中。在循环内部,我想删除每个数据帧中的行索引 0,并添加一个名为“日期”的新列。我使用以下代码:

import time

start_time = time.time()

df_total = pd.DataFrame()

for i in range(0, len(dataframe_csv)):
    df = pd.read_csv(dataframe_csv[i])
    df = df.drop(index=df.index[0], axis=0)
    df = df.assign(Date = date_list[i])
        
    df_total.append(df,ignore_index=True)

elapsed_time = time.time() - start_time
print(elapsed_time)

问题是,上面的代码确实有效,但我在循环期间用 pandas 读取的任何数据帧似乎都没有附加数据帧“df_total”。我尝试使用以下代码查看数据框的维度:

df_total.shape

上面的代码返回值(0,0),表示数据框“df_total”还是空的。

【问题讨论】:

    标签: python pandas dataframe loops append


    【解决方案1】:

    我终于找到了这个问题的答案。所以我可以使用以下代码:

    import time
    
    start_time = time.time()
    
    df_total = pd.DataFrame()
    
    for i in range(0, len(dataframe_csv)):
        df = pd.read_csv(dataframe_csv[i])
        df = df.drop(index=df.index[0], axis=0)
        df = df.assign(Date = date_list[i])
        df_total = df_total.append(df, ignore_index = True)
        print(f"Merging a total of {i} Data Frames - Total Rows = {len(df_total)}")
        
    elapsed_time = time.time() - start_time
    print(elapsed_time/60)
    

    请注意,我忘记在之前的代码中分配附加的数据框。现在代码成功合并成一个巨大的数据框。我还添加了一个打印功能,以便我能够跟踪在特定时刻合并了多少数据框。这样,我就可以知道合并过程在哪里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-23
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2018-05-13
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多