Python 美化组将数据组织到dataframe表中

Python 美化组将数据组织到dataframe表中,python,pandas,dataframe,beautifulsoup,Python,Pandas,Dataframe,Beautifulsoup,我一直在与BeautifulSoup合作,尝试整理一些我从网站(html)中提取的数据。我已经能够将这些数据浓缩,但我一直在思考如何: 消除不需要的信息 组织要放入数据帧的剩余数据 以下是我正在使用的代码: import urllib.request from bs4 import BeautifulSoup as bs import re import pandas as pd import requests headers = requests.utils.default_headers(

我一直在与BeautifulSoup合作,尝试整理一些我从网站(html)中提取的数据。我已经能够将这些数据浓缩,但我一直在思考如何:

  • 消除不需要的信息
  • 组织要放入数据帧的剩余数据
  • 以下是我正在使用的代码:

    import urllib.request
    from bs4 import BeautifulSoup as bs
    import re
    import pandas as pd
    import requests
    
    headers = requests.utils.default_headers()
    headers.update({
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
    })
    
    url = 'https://www.apartments.com/lehi-ut/1-bedrooms/'
    
    page = requests.get(url,headers = headers)
    
    soup = bs(page.text)
    
    names = soup.body.findAll('tr')
    function_names = re.findall('th class="\w+', str(names))
    function_names = [item[10:] for item in function_names]
    
    description = soup.body.findAll('td')
    #description = re.findall('td class="\w+', str(description))
    
    data = pd.DataFrame({'Title':function_names,'Info':description})
    
    我得到的错误是数组编号不匹配,我知道这是真的,但当我取消第二个描述行的哈希标记时,它会从那里删除我想要的编号,即使这样,表也无法正确组织

    我希望输出是这样的:

    (标题)标题:位置|工作室| 1 BR | 2 BR | 3 BR
    (新行)数据:德克萨斯州莱希|$1335 |$1309 |$1454 |$1580
    
    这真的是我所需要的,但我不能让BS或熊猫做得很好


    任何帮助都将不胜感激

    试试下面的方法。它首先提取表中的所有数据,然后对其进行转置(用行交换列):

    提供以下类型的输出:

    studio1br2br3br
    0       0     729   1,041   1,333
    1  $1,335  $1,247  $1,464  $1,738
    
    你在计算平均值吗?不,信息已经包含在工作表中了,所以没有数学只是试图组织一些!谢谢你的帮助!
    import urllib.request
    from bs4 import BeautifulSoup as bs
    import re
    import pandas as pd
    import requests
    
    headers = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
    }
    
    url = 'https://www.apartments.com/lehi-ut/1-bedrooms/'
    page = requests.get(url, headers=headers)
    soup = bs(page.text, 'lxml')
    table = soup.find("table", class_="rentTrendGrid")
    rows = []
    
    for tr in table.find_all('tr'):
        rows.append([td.text for td in tr.find_all(['th', 'td'])])
    
    #header_row = rows[0]
    rows = list(zip(*rows[1:])) # tranpose the table
    df = pd.DataFrame(rows[1:], columns=rows[0])
    print(df)