【问题标题】:A table into a graph (beautifulsoup in python )一张表变成一张图(python中的beautifulsoup)
【发布时间】:2016-11-06 22:48:32
【问题描述】:

有可能(是否有简单的方法)从网站中获取表格,然后将其转换为图表而不是表格?

这是代码将表格提取到表格中的代码。

导入用于查询网站的库

import urllib2

#specify the url
wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"

#Query the website and return the html to the variable 'page'
page = urllib2.urlopen(wiki)


#import the Beautiful soup functions to parse the data returned from the website
from bs4 import BeautifulSoup


#Parse the html in the 'page' variable, and store it in Beautiful Soup format
soup = BeautifulSoup(page)



all_tables=soup.find_all('table')


right_table=soup.find('table', class_='wikitable sortable plainrowheaders')
right_table





#Generate lists
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
for row in right_table.findAll("tr"):
    cells = row.findAll('td')
    states=row.findAll('th') #To store second column data
    if len(cells)==6: #Only extract table body not heading
        A.append(cells[0].find(text=True))
        B.append(states[0].find(text=True))
        C.append(cells[1].find(text=True))
        D.append(cells[2].find(text=True))
        E.append(cells[3].find(text=True))
        F.append(cells[4].find(text=True))
        G.append(cells[5].find(text=True))

#import pandas to convert list to data frame
import pandas as pd
df=pd.DataFrame(A,columns=['Number'])
df['State/UT']=B
df['Admin_Capital']=C
df['Legislative_Capital']=D
df['Judiciary_Capital']=E
df['Year_Capital']=F
df['Former_Capital']=G
df

【问题讨论】:

  • 什么图?你的意思是一些情节? pandas 具有绘图功能 - 检查文档。
  • 是的,一个简单的情节。
  • df.plot() ? pandas 使用 matplotlib 以便您可以在 matplotlib 文档中找到更多信息。
  • 我是这方面的初学者(如果我可以说一周大)。我试图找出自己的解决方案。但是,我们将非常感谢您对代码的任何帮助。

标签: python pandas beautifulsoup


【解决方案1】:

您可以使用read_html 并通过[1] 选择第二个表(read_html 从网页中的所有表中返回list of DataFrames)和DataFrame.plot

df = pd.read_html('https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India', header=0, index_col=0)[1]
print (df)

import matplotlib.pyplot as plt
#there are 2 values of year, if need first add [0] if secind add [1] after split()
df.loc[2, 'Year capital was established'] = df.loc[2, 'Year capital was established'].split()[0]
df.loc[21, 'Year capital was established'] = df.loc[21, 'Year capital was established'].split()[0]
#convert to number years
df['Year capital was established'] = df['Year capital was established'].astype(int)
df.plot(x='Judiciary capitals', y='Year capital was established')
plt.show()

【讨论】:

  • 这是一个完美的答案。只需问一件事 df.loc[2, 和 df.loc[21 你是怎么得到这些数字的?
  • 好问题。更容易的是在一个单元格中多年的 html 页面中检查表格。更通用的解决方案是使用带有 errors='coerce' 的函数 to_numeric - 它为非数字值返回 Nan,然后可以通过 isnull 函数检查索引。类似 df[pd.to_numeric(df['Year capital was established'], errors='coerce').isnull()].index
【解决方案2】:

您可以使用 Pandas 的 readhtml 函数,您只需要一个包含一些良好数字数据的表格(请参阅下面的 sn-p 中的那个)。然后使用plot 函数,你就有了一个很好的起点。

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_html('https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_area', header=0, index_col=0, skiprows=1)[1]
df.plot(x='sq mi', y='sq mi.2', kind='scatter')
plt.xlabel('Total area [sq mi]')
plt.ylabel('Water [sq mi]')
plt.show()

【讨论】:

  • 这对我来说也是一个非常清楚的例子,我想对于每个初学者来说,感谢马克西米利安彼得斯先生(y)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
  • 2017-09-01
  • 2021-11-21
  • 1970-01-01
相关资源
最近更新 更多