【问题标题】:.txt file to Pandas dataframe.txt 文件到 Pandas 数据框
【发布时间】:2018-04-19 00:17:28
【问题描述】:

我想提取 .txt 文件的列并将它们放入 pandas DataFrame 或 csv。我还需要从 .txt 文件的标题中提取一些信息,并将它们作为列添加到 dataframe/csv 中。

这里是文件http://meteosearch.meteo.gr/data/askyfou/2017-01.txt的链接

Partial screenshot of the file

提前感谢您的帮助!

【问题讨论】:

  • SO 不是编码服务,它显示了您尝试过的内容。

标签: python pandas csv text web-scraping


【解决方案1】:

尝试类似:

import pandas as pd
import requests
import StringIO

f = StringIO.StringIO()
r = requests.get('http://meteosearch.meteo.gr/data/askyfou/2017-01.txt').content
f.write(r)

f.seek(0)
df = pd.DataFrame()

for x in f.readlines()[10:41]:
    df = df.append(pd.Series(x.split()),ignore_index=True)

df.columns = ['DAY','MEAN TEMP','HIGH1','TIME1','LOW',
              'TIME2','MAX RH','MIN RH','RAIN',
              'AVG WIND SPEED','HIGH2','TIME3','DOM DIR']

print df.head()

【讨论】:

    【解决方案2】:

    感谢医生的回复。

    我试过这段代码

    指定列宽

    col_specification =[(0, 4), (5, 9), (11, 15), (16, 23), (24, 28), (29, 36), (37, 44),(45 , 49), (51, 55), (58, 63), (64,69)]

    从url读取数据

    data = pd.read_fwf('http://meteosearch.meteo.gr/data/askyfou/2017-01.txt', colspecs=col_specification, header = 8, skipfooter = 2, skipinitialspace = True)

    它似乎工作,虽然它不像你的那样自动化。 我假设你使用 python 2,对吧?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-10
      • 2020-06-13
      • 2021-05-30
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2017-06-27
      • 2017-03-11
      相关资源
      最近更新 更多