列表中数据的最佳分离方法

1 投票
1 回答
45 浏览
提问于 2025-04-14 16:46

根据一个网站上的统计信息,我写了一段基本的网页抓取代码,代码如下:

import re
import requests
from bs4 import BeautifulSoup
content = requests.get("https://www.geostat.ge/ka/modules/categories/26/samomkhmareblo-fasebis-indeksi-inflatsia")
content = BeautifulSoup(content.content, 'html.parser')
#print(content.prettify())
information = []
for row in content.select('tbody tr'):
    for data in row.find_all('td'):
        if len(data.text.strip()) != 0:
            information.append(data.text.strip())
print(information)

这段代码返回了以下信息:

['2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', 'საშუალო წლიური წინა წლის საშუალო წლიურთან', '99.1', '99.5', '103.1', '104.0', '102.1', '106.0', '102.6', '104.9', '105.2', '109.6', '111.9', '102.5', 'დეკემბერი წინა წლის დეკემბერთან', '98.6', '102.4', '102.0', '104.9', '101.8', '106.7', '101.5', '107.0', '102.4', '113.9', '109.8', '100.4'

现在,文本前面的部分包含了“საშუალო”这个年份,后面的部分是两个文本之间的通货膨胀数据,所以我写了这段比较手动的代码:

years = []
average_annual = []
december = []

first_index = information.index('საშუალო წლიური წინა წლის საშუალო წლიურთან')
second_index = information.index('დეკემბერი წინა წლის დეკემბერთან')
for i in range(0, first_index):
    years.append(int(information[i]))
print(years)
for  i in range(first_index + 1, second_index):
    average_annual.append(float(information[i]))
print(average_annual)
for i in range(second_index + 1, len(information)):
    december.append(float(information[i]))
print(december)

这段代码能正确地分隔这些信息:

[2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023]
[99.1, 99.5, 103.1, 104.0, 102.1, 106.0, 102.6, 104.9, 105.2, 109.6, 111.9, 102.5]
[98.6, 102.4, 102.0, 104.9, 101.8, 106.7, 101.5, 107.0, 102.4, 113.9, 109.8, 100.4]

有没有更好的方法来做到这一点呢?

我尝试了这个版本:

data = pd.DataFrame(pd.read_html("https://www.geostat.ge/ka/modules/categories/26/samomkhmareblo-fasebis-indeksi-inflatsia", encoding='utf-8')[0])
#data.drop(0, axis=0, inplace=True)
#data = data.droplevel(level=0, axis=1)
print(data)

结果是这样的:

                                          0       1   ...      11      12
0                                        NaN  2012.0  ...  2022.0  2023.0
1  საშუალო წლიური წინა წლის საშუალო წლიურთან    99.1  ...   111.9   102.5
2            დეკემბერი წინა წლის დეკემბერთან    98.6  ...   109.8   100.4

[3 rows x 13 columns]

我该如何处理这种情况呢?

1 个回答

1

对于这个网站,我建议使用 pandas.read_html 来把表格读取到一个数据框中。不过,首先你可以把第一行改成表头(<th>),这样才能得到正确的列名:

from io import StringIO

import pandas as pd
import requests
from bs4 import BeautifulSoup

url = '"https://www.geostat.ge/ka/modules/categories/26/samomkhmareblo-fasebis-indeksi-inflatsia"'
content = requests.get(url).content
soup = BeautifulSoup(content, "html.parser")

for td in soup.tr.select("td"):
    td.name = "th"

df = pd.read_html(StringIO(str(soup)))[0]
df = df.set_index(df.columns[0])
df.index.name = None

print(df)

输出结果:

                                           2012   2013   2014   2015   2016   2017   2018   2019   2020   2021   2022   2023
საშუალო წლიური წინა წლის საშუალო წლიურთან  99.1   99.5  103.1  104.0  102.1  106.0  102.6  104.9  105.2  109.6  111.9  102.5
დეკემბერი წინა წლის დეკემბერთან            98.6  102.4  102.0  104.9  101.8  106.7  101.5  107.0  102.4  113.9  109.8  100.4

撰写回答