13

我试图通过简单地传递日期和时间来删除 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

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

:-)

4

2 回答 2

19

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

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')
于 2013-05-17T16:26:10.813 回答
1

或者,这也有效:

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)
于 2020-04-15T12:22:49.570 回答