pandas 从时间索引数据框中删除一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16613187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:50:07  来源:igfitidea点击:

Deleting a Row from a Time Indexed Dataframe

pandastime-seriesdelete-rowdataframe

提问by Markus W

I'm trying to delete a row in a Pandas dataframe by simply passing the date and time.

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

The dataframe has the following structure:

数据框具有以下结构:

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

I have been trying with df = df.drop('2012-01-01 01:00:00')

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

But I keep getting the following error message:

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

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

Any help on either deleting the row or just deleting the values would be much appreciated.

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

:-)

:-)

回答by Andy Hayden

It looks like you have to actually use the Timestamp rather than the string:

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

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

Assuming DateTime is the index, if not use

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

df1 = df.set_index('Date_Time')

回答by Rens

Alternatively, this works, too:

或者,这也有效:

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

It's also handy when you like to drop a range of observations based on the datetime index. E.g. all observations later than 2012-01-01 01:00:00:

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

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