[英]How do I split data out from one column of a pandas dataframe into multiple columns of a new dataframe
[英]How do I split a pandas dataframe column into 3 unique columns?
我有一个带有大学篮球投注赔率的 dataframe。 我需要将第一列“游戏”分成“时间”、“家”、“离开”。 主队是“比赛”dataframe 中列出的最后一支球队。
数据正在通过漂亮的汤被刮到数据框中。
import pandas as pd # library for data analysis
import numpy as np
import requests # library to handle requests
from bs4 import BeautifulSoup # library to parse HTML documents
url = "https://vegasinsider.com/college-basketball/odds/las-vegas/"
response=requests.get(url)
print(response.status_code)
soup = BeautifulSoup(response.text, 'html.parser')
indiatable=soup.find('table',{'class':"frodds-data-tbl"})
df=pd.read_html(str(indiatable))
# convert list to dataframe
df=pd.DataFrame(df[0])
print(df.head())
df.columns =['game', 'open','consensus','betmgm','caesars','fanduel','draftkings','pointsbet','wynn','superbook']
df
我需要帮助将第一列分成三列。 这是我正在使用的代码。
df[['time', 'home', 'away']] = df['game'].str.split(expand=True)
我需要新的数据框看起来像:
df = pd.DataFrame ({'time': ['02/02 7:00 PM'], 'home': ['Furman'], 'away': ['The Citadel']})
每个请求, df[['game']].to_dict()
的 output 是:
{'game': {0: '02/02 7:00 PM 665\xa0The Citadel 666\xa0Furman'}}
先感谢您!
您可以在"\xa0"
上使用str.split
,并使用str.rstrip
右侧的数字:
import string
df[['time','home','away']] = df['game'].str.split('\xa0', expand=True).apply(lambda col: col.str.rstrip(string.digits), axis=0)
df = df.drop(columns='game')
Output:
time home away
0 02/02 7:00 PM The Citadel Furman
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.