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

python datetime index-无法删除日期-valueerror:无法将字符串转换为时间戳

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

    在第二个日期时间索引筛选器之后,无法从数据帧中删除日期。我得到这个错误: ValueError: could not convert string to Timestamp .

    创建基本数据集(只需首先运行此代码段,创建数据帧大约需要45秒):

    #2016
    url = "https://www.ndbc.noaa.gov/view_text_file.php?filename=42040h2016.txt.gz&dir=data/historical/stdmet/"
    data_csv = urlopen(url)
    df = pd.read_csv(data_csv, delim_whitespace=True, index_col=0, parse_dates=True)
    
    
    ############################################################
    # Buoy 42040 Data Preparation
    ############################################################
    
    #Remove useless variables
    df.drop(['WDIR', 'WSPD', 'GST', 'WVHT', 'DPD', 'APD', 'MWD', 'PRES', 'VIS', 'TIDE', 'VIS'], 
            axis = 1, inplace = True)
    
    #Reset Index
    df.reset_index(level=0, inplace=True)
    
    #remove 1st row contains erronous characters
    df = df.iloc[1:]
    
    #Rename Year column
    df = df.rename(columns={'#YY': 'YY'})
    
    #drop rows containing headers / strings 
    df.iloc[24070:24080,:] #24077
    df = df[df.MM.str.contains("mo") == False]
    
    #Create date column then merge
    df['Date'] = df[df.columns[0:3]].apply(lambda x: '/'.join(x.dropna().astype(int).astype(str)),axis=1)
    df['Time'] = df[df.columns[3]].str.cat(df[df.columns[4]], sep=':')
    df['Date.Time'] = df['Date'] + ':' + df['Time']
    
    #Convert to numeric from objects 
    df = df.convert_objects(convert_numeric=True)
    
    #Convert Date and Date.Time to pd.datetime classes
    df['Date'] = pd.to_datetime(df['Date'], format = '%Y/%m/%d')
    df['Date.Time'] = pd.to_datetime(df['Date.Time'], format='%Y/%m/%d:%H:%M', utc=True)
    
    #Convert dataframe index to a datetime index, then drop other times
    df = df.set_index('Date.Time')
    df.drop(['hh', 'mm', 'Time', 'Date'], axis = 1, inplace = True)
    #Remove 2014 data
    df = df[df['YY'] != 2014]
    

    检查日期时间索引是否有效。看起来不错。

    df.info()
    <class 'pandas.core.frame.DataFrame'>
    DatetimeIndex: 111356 entries, 2015-01-01 00:50:00+00:00 to 2018-09-04 00:00:00+00:00
    Data columns (total 6 columns):
    YY      111356 non-null int64
    MM      111356 non-null int64
    DD      111356 non-null int64
    ATMP    89208 non-null float64
    WTMP    110737 non-null float64
    DEWP    89221 non-null float64
    dtypes: float64(3), int64(3)
    memory usage: 5.9 MB
    

    将2016年2月和3月的数据从数据框中删除,因为它是坏的。这里没问题:

    df = df.loc[(df.index <= '2016-01-31') | (df.index >= '2016-04-01')]
    

    将2016年12月从数据框架中删除,因为它也很糟糕,但随后出现了一个问题:

    df = df.loc[(df.index <= '2016-11-31') | (df.index >= '2017-01-01')]
    
    ValueError: could not convert string to Timestamp
    

    如果有其他的方法,任何人都会建议这样做。

    谢谢!

    2 回复  |  直到 6 年前
        1
  •  2
  •   MichaelCG8    6 年前

    你把第一个日期定为2016年11月31日,但11月只有30天。把那行改成 df = df.loc[(df.index <= '2016-11-30') | (df.index >= '2017-01-01')] 看看它是否能解决你的问题。

        2
  •  0
  •   Starbucks    6 年前

    我找到了答案:我查看了我要删除的数据,而过滤器出错的是这些数据。如果我删除下面的命令,它不会影响代码的其余部分。

    df = df[df.MM.str.contains("mo") == False]

    谢谢你看这篇文章!