简体   繁体   中英

How do I split a pandas dataframe column into 3 unique columns?

I have a dataframe with college basketball betting odds. I need to split the first column 'game' into 'time', 'home', 'away'. The home team is the last team listed in the 'game' dataframe.

The data is being scraped into a data frame via beautiful soup.

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

抓取的数据框

I need help splitting the first column into three columns though. This is the code I am using.

df[['time', 'home', 'away']] = df['game'].str.split(expand=True)

I need to new data frame to look like:

df = pd.DataFrame ({'time': ['02/02 7:00 PM'], 'home': ['Furman'], 'away': ['The Citadel']})

在此处输入图像描述

Per requests, the output of df[['game']].to_dict() is:

{'game': {0: '02/02 7:00 PM  665\xa0The Citadel  666\xa0Furman'}}

Thank you in advance!

You could use str.split on "\xa0" , and use str.rstrip to strip the digits on the right:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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