簡體   English   中英

如何將 pandas dataframe 列拆分為 3 個唯一列?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM