【问题标题】:Making pandas dataframe by using strings使用字符串制作熊猫数据框
【发布时间】:2017-03-13 13:06:50
【问题描述】:

大家好,

我尝试将数据框列设为“日期”并将日期时间添加到列行。日期时间在字符串列表中每 5 次出现一次。

我认为像 range(start,end,step) 这样的方法会很好,但在实践中如何实现呢?

这是我的代码:

import requests, re, pandas
from bs4 import BeautifulSoup

r=requests.get("http://www.hltv.org/?pageid=188&statsfilter=2816&offset=0")
c=r.content

soup=BeautifulSoup(c,"html.parser")


for string in soup.find_all("div",{"class":"covSmallHeadline"})[6:]:
    print(string.text.replace("(","").replace(")",""))

这是输出(实际列表大小更大):

5/3 17
 Astralis 16
 FaZe 13
inferno
IEM Katowice 2017
5/3 17
 Astralis 16
 FaZe 12
nuke
IEM Katowice 2017
5/3 17
 Astralis 16
 FaZe 12
overpass
IEM Katowice 2017
5/3 17
 FaZe 16
 Astralis 9
cache
IEM Katowice 2017
4/3 17
 Astralis 16
 Heroic 12
nuke
IEM Katowice 2017
4/3 17
 Astralis 16
 Heroic 12
train
IEM Katowice 2017
4/3 17
 Immortals 10
 FaZe 16
mirage
IEM Katowice 2017
4/3 17
 FaZe 16
 Immortals 9
inferno
IEM Katowice 2017
3/3 17
 Natus Vincere 2
 Astralis 16
nuke
IEM Katowice 2017

【问题讨论】:

  • 您能否澄清一下您想从输入中获得哪种输出(DataFrame、Series)?我现在还不清楚。
  • 我试图让 pandas.DataFrame 输出。

标签: python pandas dataframe beautifulsoup


【解决方案1】:

先将数据转成CSV:

import re
In [83]: for row in table.find_all('div', style=re.compile(r'width:606px;height:22px;background-color')):
   ...:      print(row.get_text(strip=True, separator=','))


5/3 17,Astralis (16),FaZe (13),inferno,IEM Katowice 2017
5/3 17,Astralis (16),FaZe (12),nuke,IEM Katowice 2017
5/3 17,Astralis (16),FaZe (12),overpass,IEM Katowice 2017

【讨论】:

  • 我会问因为学习,这行:'width:606px;height:22px;background-color'实际上是做什么的?
  • @Juho M 这是样式属性,我使用此字符串定位每一行。因为每一行的样式都不一样,所以我用re来匹配它们相同的部分。crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression
猜你喜欢
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 2015-06-25
  • 2018-11-03
  • 2017-01-13
  • 1970-01-01
相关资源
最近更新 更多