如何以Pythonic方式将美国气象局历史水位数据导入Pandas
简洁实现:将美国气象局历史水位数据导入Pandas DataFrame
需求说明
需要将目标网页的历史水位数据整理为指定格式的Pandas DataFrame,追求简洁的Pythonic实现,替代手动解析为列表字典的方式。
最优实现代码
利用Pandas自带的read_html方法直接解析网页表格,无需手动处理HTML文本,代码极简:
import pandas as pd # 目标网页地址 url = "https://water.weather.gov/ahps2/crests.php?wfo=jan&gage=jacm6&crest_type=historic" # 读取网页中匹配"Historic Crests"的表格 dfs = pd.read_html(url, match="Historic Crests") df = dfs[0] # 清洗数据并整理列格式 df.columns = ["No.", "Crest", "Date"] df["No."] = df["No."].str.extract(r'(\d+)').astype(int) df["Crest"] = df["Crest"].str.extract(r'(\d+\.\d+)').astype(float) # 输出结果 print(df)
最终DataFrame结构
| No. | Crest | Date |
|---|---|---|
| 1 | 43.28 | 04/17/1979 |
| 2 | 39.58 | 05/25/1983 |
| 3 | 36.67 | 02/17/2020 |
内容的提问来源于stack exchange,提问作者Juancheeto
相关产品推荐
相关产品推荐

