Python 创建多行标题的数据帧

Python 创建多行标题的数据帧,python,pandas,Python,Pandas,我尝试使用的熊猫数据框打印不正确 from urllib.request import urlopen from bs4 import BeautifulSoup import pandas as pd pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) year = 2021 url = "https://www.basketball-reference.com/le

我尝试使用的熊猫数据框打印不正确

from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

year = 2021
url = "https://www.basketball-reference.com/leagues/NBA_{}_per_game.html".format(year)
html = urlopen(url)
soup = BeautifulSoup(html, features='html.parser')
soup.findAll('tr', limit=2)
headers = [th.getText() for th in soup.findAll('tr', limit=2)[0].findAll('th')]
headers = headers[1:]
rows = soup.findAll('tr')[1:]
player_stats = [[td.getText() for td in rows[i].findAll('td')] for i in range(len(rows))]
stats = pd.DataFrame(player_stats, columns=headers)
stats.head(10)

with open('stats.txt', 'w') as f:
   f.write(str(stats)

在输出中,它放置前几个标题和行。然后,在完成所有行之后,它将执行下一组标题,因为您正在写入文件,pandas'to_csv()对您不起作用吗

stats.to_csv('stats.csv', ignore_index=True)

to_csv有很多可参数化的选项。

我将把Octav的观点放远一点。不仅让pandas写入文件,而且让它解析表

import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

year = 2021
url = "https://www.basketball-reference.com/leagues/NBA_{}_per_game.html".format(year)
stats = pd.read_html(url)[0]
stats = stats[stats['Rk'].ne('Rk')] #<-- removes rows with the "headers"

stats.head(10)

stats.to_csv('stats.csv', index=False)
将熊猫作为pd导入
pd.set\u选项('display.max\u columns',无)
pd.set\u选项('display.max\u rows',无)
年份=2021年
url=”https://www.basketball-reference.com/leagues/NBA_{}{u per_game.html”。格式(年份)
stats=pd.read\uHTML(url)[0]

stats=stats[stats['Rk'].ne('Rk')]#好的,谢谢你的帮助。