代码之家  ›  专栏  ›  技术社区  ›  Starbucks

导入URL数据属于一个索引Python

  •  0
  • Starbucks  · 技术社区  · 6 年前

    我正在尝试从国家海洋和大气协会导入数据。数据可以以txt格式手动下载,但我想通过Python的urlopen下载。导入数据后,所有列和行都位于一个索引列中,而不是一个带有标题的标准数据框。任何信息都会有帮助。

    import pandas as pd
    from urllib.request import urlopen
    
    url = "https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h2014.txt.gz&dir=data/historical/stdmet/"
    #df = pd.read_csv(url, header=NONE, sep='\s+')
    data_csv = urlopen(url)
    df2014 = pandas.read_csv(data_csv, index_col=0, parse_dates=True)
    
    df2014.head()
    

    结果:

    df2014.head()
    Out[26]: 
    Empty DataFrame
    Columns: []
    Index: [#yr  mo dy hr mn degT m/s  m/s     m   sec   sec degT   hPa  degC  degC  degC   mi    ft, 2014 01 01 00 00  61  7.4 99.0  1.12  4.34 99.00 999 9999.0  19.2 999.0  12.5 99.0 99.00, 2014 01 01 00 20  60  7.8 99.0  1.12  4.34 99.00 999 9999.0  19.4 999.0  12.9 99.0 99.00, 2014 01 01 00 40  66  7.8 99.0  1.12  4.34 99.00 999 9999.0  19.3 999.0  13.0 99.0 99.00, 2014 01 01 01 00  76  8.6 99.0  1.18  4.49 99.00 999 9999.0  19.4 999.0  13.3 99.0 99.00]
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   hornhound    6 年前

    read_csv pandas 库以逗号作为分隔符读取数据。

    delim_whitespace 中的参数 True

    df2014 = pd.read_csv(data_csv, delim_whitespace=True, index_col=0, parse_dates=True)
    
        2
  •  0
  •   Oliver Weissbarth    6 年前

    pandas.read\u csv使用''作为默认分隔符。列之间用空格隔开。您可以告诉pandas使用空格作为分隔符,方法是 sep='\s+' (正如您在评论行中所做的)或 delim_whitespace=True 作为关键字参数。 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html