如何删除 Pandas 数据框中特定日期的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35372499/
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-14 00:41:23  来源:igfitidea点击:

How can I delete rows for a particular Date in a Pandas dataframe?

pythonpandas

提问by omkar

I've got a Pandas DataFrame using Date as an index. How can I drop all rows that have the date "2000-01-06"?

我有一个使用 Date 作为索引的 Pandas DataFrame。如何删除所有日期为“2000-01-06”的行?

Sample code:

示例代码:

import numpy as np
import pandas as pd

dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 3), index=dates, columns=['A', 'B', 'C'])
df.index.name = 'Date'

Example DataFrame:

示例数据帧:

                   A         B         C
Date                                    
2000-01-01 -0.501547 -0.227375  0.275931
2000-01-02  0.994459  1.266288 -0.178603
2000-01-03 -0.982746 -0.339685  0.157390
2000-01-04 -1.013987 -1.074076 -2.346117
2000-01-05 -0.101157 -0.698663  1.025318
2000-01-06 -1.697615 -0.081638  1.075712
2000-01-07  0.617587 -1.561204 -1.685774
2000-01-08  0.049115  0.579139 -1.036961

回答by EdChum

You can pass a datetime to dropto drop that row:

您可以将日期时间传递drop给删除该行:

In [12]:
df.drop(pd.to_datetime('2000-01-06'))

Out[12]:
                   A         B         C
Date                                    
2000-01-01 -0.401531 -1.076727  0.519324
2000-01-02  0.022450  0.655763 -0.592045
2000-01-03  0.579927  1.358475  0.803414
2000-01-04  0.346246 -0.252332 -1.347014
2000-01-05  0.101308  0.912279  0.020754
2000-01-07  0.869264  0.699575  0.385521
2000-01-08  0.098829 -0.237605  1.112033

回答by tsando

You can also drop a list of values, e.g.:

您还可以删除值列表,例如:

date_list = [datetime(2009, 5, 2),
             datetime(2010, 8, 22),
             datetime(2010, 9, 19),
             datetime(2011, 6, 19),
             datetime(2011, 7, 17),
             datetime(2015, 5, 23),
             datetime(2016, 2, 20)]
df = df.drop(date_list)

Note that by putting inplace=True in the drop argument you don't have to define a new object, but it is done on the same object

请注意,通过将 inplace=True 放在 drop 参数中,您不必定义新对象,但它是在同一个对象上完成的

df.drop(date_list, inplace=True)