简体   繁体   English

如何使用panda for python同时添加多个列

[英]How to append multiple columns at the same time using panda for python

I am currently using python to web scrape the three-point statistics for every NBA player and am trying to put this data in a data frame. 我目前正在使用python抓取每个NBA球员的三点统计数据,并试图将这些数据放在一个数据框中。 The code below is my attempt at adding the values to the data frame. 下面的代码是我尝试将值添加到数据框中的尝试。 The variables players,teams,threePointAttempts, and threePointPercentage are all lists containing 50 values. 变量players,teams,threePointAttempts和ThreePointPercentage都是包含50个值的列表。 These are refilled after every iteration of the while loop because the script moves through each page of the NBA site. 在while循环的每次迭代之后,这些内容都会重新填充,因为脚本会在NBA网站的每一页中移动。

while i<10:
soup = BeautifulSoup(d.page_source, 'html.parser').find('table')
headers, [_, *data] = [i.text for i in soup.find_all('th')], [[i.text for i in b.find_all('td')] for b in soup.find_all('tr')]
final_data = [i for i in data if len(i) > 1]

data_attrs = [dict(zip(headers, i)) for i in final_data]
print(data_attrs)

players = [i['PLAYER'] for i in data_attrs]
teams = [i['TEAM'] for i in data_attrs]
threePointAttempts = [i['3PA'] for i in data_attrs]
threePointPercentage = [i['3P%'] for i in data_attrs]


data_df = data_df.append(pd.DataFrame(players, columns=['Player']),ignore_index=True)
data_df = data_df.append(pd.DataFrame(teams, columns=['Team']),ignore_index=True)
data_df = data_df.append(pd.DataFrame(threePointAttempts, columns=['3PA']),ignore_index=True)
data_df = data_df.append(pd.DataFrame(threePointPercentage, columns=['3P%']),ignore_index=True)
data_df = data_df[['Player','Team','3PA','3P%']]

The issue I am having is the data frame fills like this: 我遇到的问题是数据框填充如下:

First column Second column Third column 第一栏 第二栏 第三栏

Try: 尝试:

temp_df = pd.DataFrame({'Player': players,
                        'Team': teams,
                        '3PA': threePointAttempts,
                        '3P%': threePointPercentage})

data_df = data_df.append(temp_df, ignore_index=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM