【发布时间】:2019-01-05 15:17:47
【问题描述】:
我正在学习通过 Python 从网站上抓取数据。从this page 提取有关旧金山的天气信息。我在将数据组合到 Pandas Dataframe 时卡住了。是否可以创建每行具有不同长度的数据框?
我已经根据此处的答案尝试了 2 种方法,但它们并不是我想要的。两个答案都将 temps 列的值向上移动。 Here is the screen what I try to explain..
第一种方式:https://stackoverflow.com/a/40442094/10179259
第二种方式:https://stackoverflow.com/a/19736406/10179259
import requests
from bs4 import BeautifulSoup
import pandas as pd
page = requests.get("http://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168")
soup = BeautifulSoup(page.content, 'html.parser')
seven_day = soup.find(id="seven-day-forecast")
forecast_items = seven_day.find_all(class_="tombstone-container")
periods=[pt.get_text() for pt in seven_day.select('.tombstone-container .period-name')]
short_descs=[sd.get_text() for sd in seven_day.select('.tombstone-container .short-desc')]
temps=[t.get_text() for t in seven_day.select('.tombstone-container .temp')]
descs = [d['alt'] for d in seven_day.select('.tombstone-container img')]
#print(len(periods), len(short_descs), len(temps), len(descs))
weather = pd.DataFrame({
"period": periods, #length is 9
"short_desc": short_descs, #length is 9
"temp": temps, #problem here length is 8
#"desc":descs #length is 9
})
print(weather)
我希望 temp 列的第一行是 Nan。谢谢。
【问题讨论】:
-
回答您的问题“是否可以创建每行具有不同长度的数据框?”:不,这是不可能的,除非您用 NaN 填充其他列。但通常这不是正确的方法。