python - 将多个 reshape 列表附加到 pandas DataFrame 中

标签 python pandas dataframe beautifulsoup iteration

我正在废弃英格兰的联合数据,并在一次处理一家医院时以我想要的正确格式获得结果。我最终想要迭代所有医院,但首先决定创建三个不同医院的数组并找出迭代。

当我只有一家医院时,下面的代码为我提供了 pandas DataFrame 中最终结果的正确格式:

import requests
from bs4 import BeautifulSoup
import pandas
import numpy as np
r=requests.get("http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?
hospitalName=Norfolk%20and%20Norwich%20Hospital")
c=r.content
soup=BeautifulSoup(c,"html.parser")

all=soup.find_all(["div"],{"class":"toggle_container"})[1]

i=0
temp = []
for item in all.find_all("td"):
    if i%4 ==0:
        temp.append(soup.find_all("span")[4].text)
        temp.append(soup.find_all("h5")[0].text)
    temp.append(all.find_all("td")[i].text.replace("   ",""))
    i=i+1
table = np.array(temp).reshape(12,6)
final = pandas.DataFrame(table)
final

在我的迭代版本中,我无法找到将每个结果集附加到最终 DataFrame 中的方法:

hosplist = ["http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Norfolk%20and%20Norwich%20Hospital",
            "http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Barnet%20Hospital",
            "http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Altnagelvin%20Area%20Hospital"]
temp2 = []
df_final = pandas.DataFrame()
for item in hosplist:
    r=requests.get(item)
    c=r.content
    soup=BeautifulSoup(c,"html.parser")

    all=soup.find_all(["div"],{"class":"toggle_container"})[1]
    i=0
    temp = []
    for item in all.find_all("td"):
        if i%4 ==0:
            temp.append(soup.find_all("span")[4].text)
            temp.append(soup.find_all("h5")[0].text)
        temp.append(all.find_all("td")[i].text)
        i=i+1
    table = np.array(temp).reshape((int(len(temp)/6)),6)
    temp2.append(table)
    #df_final = pandas.DataFrame(df)

最后,“表”包含了我想要的所有数据,但它不容易操作,所以我想将其放入 DataFrame 中。但是,我收到“ValueError:必须通过二维输入”错误。

我认为这个错误是说我有 3 个数组,这将使它成为 3 维的。这只是一个实践迭代,我计划将超过 400 家医院的数据放入数据框中,但现在我被困在这里。

最佳答案

您的问题的简单答案是 HERE .

最困难的部分是获取代码并找出还不正确的地方。

使用您的完整代码,我对其进行了修改,如下所示。请复制并与您的进行比较。

import requests
from bs4 import BeautifulSoup
import pandas
import numpy as np

hosplist = ["http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Norfolk%20and%20Norwich%20Hospital",
            "http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Barnet%20Hospital",
            "http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Altnagelvin%20Area%20Hospital"]
temp2 = []
df_final = pandas.DataFrame()
for item in hosplist:
    r=requests.get(item)
    c=r.content
    soup=BeautifulSoup(c,"html.parser")

    all=soup.find_all(["div"],{"class":"toggle_container"})[1]
    i=0
    temp = []
    for item in all.find_all("td"):
        if i%4 ==0:
            temp.append(soup.find_all("span")[4].text)
            temp.append(soup.find_all("h5")[0].text)
        temp.append(all.find_all("td")[i].text)
        i=i+1
    table = np.array(temp).reshape((int(len(temp)/6)),6)
    for array in table:
        newArray = []
        for x in array:
            try:
                x = x.encode("ascii")
            except:
                x = 'cannot convert'
            newArray.append(x)
        temp2.append(newArray)

df_final = pandas.DataFrame(temp2, columns=['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
print df_final

我尝试使用列表理解进行 ascii 转换,这对于字符串在数据帧中显示是绝对必要的,但是理解抛出了错误,所以我构建了一个异常,并且该异常从未显示。

关于python - 将多个 reshape 列表附加到 pandas DataFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47444269/

相关文章:

Python/Pygame 颜色不是元组 : unhashable type error when used as dictionary keys

python - Scrapy redirect_urls exception.KeyError

python - 将文本文件转换为 Pandas 数据框

Python:广告列,每行具有平均值

python - Emacs 组织模式 : Executing simple python code

python - 使用列中的列表整理 DataFrame 的最佳方法

python - 如何将列表数据捕获到数据框中

python - 如何减去 pandas 数据帧 1 列中的数字?

python - Pandas read_html 返回原始 HTML 内容[对于某些行/单元格/等]

python - 用 python 中的图像赢得 10 个 toast 通知