python - 使用 Pandas 作为中间人将多个 html 表导出到 Excel

标签 python excel pandas export export-to-excel

我正在从一个网站收集 1981-2018 年的数据,其中 this link显示2018年数据:

如果在上述链接中将 2018 更改为 1981-2018 年,则可以获得剩余的数据集。

使用Pandasurllib.request我收集数据如下:

url = ['ftp://ftp.cpc.ncep.noaa.gov/htdocs/degree_days/weighted/daily_data/' + \
   '{}'.format(i) + '/Population.Heating.txt' for i in range(1981,2019)]
data_url = [pd.read_csv(url[i], sep=" ", header=None) for i in range(len(url))]

问题

首先,是否有比上述列表理解更干净、更有效的方式从链接收集数据?其次,如何将整个列表推导导出到 Excel 电子表格?

但是,我尝试了以下导出方法;该代码仅导出 2018 年:

from pandas import ExcelWriter

writer = ExcelWriter('PythonExport.xlsx')
for i in range(len(data_url)):
    data_url[i].to_excel(writer,'Sheet1')
writer.save()

解决为什么我不直接将数据导入Excel的问题:最终,我希望将每年的数据放在DataFrame中,即一列包含区域数据,另一列包含“圆锥”数据。在尝试构建此 DataFrame 时,在 Excel 中整理数据似乎比使用上面的列表理解 data_url 更容易,然后使用数据构建 DataFrame。

最佳答案

以下是将数据解析为单个数据帧的方法:

代码:

url = [
    'ftp://ftp.cpc.ncep.noaa.gov/htdocs/degree_days/weighted/daily_data/'
    '{}'.format(i) + '/Population.Heating.txt' for i in range(1981, 2018)]
data_url = [pd.read_csv(url[i], sep="|", skiprows=3, index_col=0).T
            for i in range(len(url))]
df = pd.concat(data_url)

print(df.head())
print(df.tail())

结果:

Region     1   2   3   4   5   6   7   8   9  CONUS
19810101  51  45  36  33  24  24  14  22  14     28
19810102  46  42  43  40  23  29  17  22  16     29
19810103  55  50  51  46  26  28  17  23  14     33
19810104  66  59  62  55  27  30  18  23  15     37
19810105  62  56  59  47  34  42  22  24  14     38

Region     1   2   3   4   5   6   7   8   9  CONUS
20171227  53  49  62  64  22  35  28  29  15     37
20171228  59  54  60  57  27  37  28  26  13     38
20171229  59  53  54  54  26  33  23  24  11     35
20171230  57  50  54  62  24  32  19  27  12     34
20171231  59  55  60  68  29  39  27  30  15     40

关于python - 使用 Pandas 作为中间人将多个 html 表导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877136/

相关文章:

python - 在 DatetimeIndex 上使用 .loc 来检索特定日期的值 (KeyError

python - pandas to_sql() 和 read_sql_query() 处理空字符串

python - 下载特定Python模块时出现问题 'Pip'

python - 如何设置 Python 的 httplib 使用的信任库?

excel - 将毫秒转换为日期(在 Excel 中)

string - Excel 函数格式

python - Pandas 查找,将数据框中的一列映射到不同数据框中的另一列

python - 在python中增加其他文件中选择的属性

python - 格式为 '%' datetime.strptime 的错误指令

c# - 如何使用c#将Excel中的一行格式复制到另一行