【问题标题】:Deleting a Row from a Time Indexed Dataframe从时间索引数据框中删除一行
【发布时间】:2013-05-12 20:47:42
【问题描述】:

我试图通过简单地传递日期和时间来删除 Pandas 数据框中的一行。

数据框的结构如下:

Date_Time             Price1   Price2    Price3                       
2012-01-01 00:00:00    63.05    41.40    68.14
2012-01-01 01:00:00    68.20    42.44    59.64
2012-01-01 02:00:00    61.68    43.18    49.81

我一直在尝试df = df.drop('2012-01-01 01:00:00')

但我不断收到以下错误消息:

exceptions.ValueError: labels [2012-01-01 01:00:00] not contained in axis

任何有关删除行或仅删除值的帮助将不胜感激。

:-)

【问题讨论】:

    标签: pandas time-series delete-row dataframe


    【解决方案1】:

    看起来你必须实际使用时间戳而不是字符串:

    In [11]: df1
    Out[11]:
                         Price1  Price2  Price3
    Date_Time
    2012-01-01 00:00:00   63.05   41.40   68.14
    2012-01-01 01:00:00   68.20   42.44   59.64
    2012-01-01 02:00:00   61.68   43.18   49.81
    
    In [12]: df1.drop(pd.Timestamp('2012-01-01 01:00:00'))
    Out[12]:
                         Price1  Price2  Price3
    Date_Time
    2012-01-01 00:00:00   63.05   41.40   68.14
    2012-01-01 02:00:00   61.68   43.18   49.81
    

    假设 DateTime 是索引,如果不使用

    df1 = df.set_index('Date_Time')
    

    【讨论】:

    • 这可能有点令人惊讶,因为 ix 使用字符串...df1.ix['2012-01-01 01:00:00']
    【解决方案2】:

    或者,这也可以:

    df1.drop(df1.loc[df1['Date_Time'] == '2012-01-01 01:00:00'].index, inplace=True)
    

    当您想根据日期时间索引删除一系列观察时,它也很方便。例如。 2012-01-01 01:00:00 之后的所有观察结果:

    df1.drop(df1.loc[df1['Date_Time'] > '2012-01-01 01:00:00'].index, inplace=True)
    

    【讨论】:

    • 问题已删除,需要df['rev_dis'] = np.where((df['date'] >= '2020-01-02') & (df['date'] <= '2020-01-03'), df['rev'] * 0.5, df['rev'])
    • 耶斯瑞尔!非常感谢!我在这方面压力太大了。非常感谢您的帮助。我只需要保持索引原样(所以不要将日期设置为索引)并且它有效!
    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2021-03-19
    • 1970-01-01
    • 2021-07-22
    • 2016-06-01
    • 1970-01-01
    相关资源
    最近更新 更多