问题
I've got a Pandas DataFrame using Date as an index. How can I drop all rows that have the date "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
回答1:
You can pass a datetime to drop to drop that row:
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
回答2:
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
df.drop(date_list, inplace=True)
来源:https://stackoverflow.com/questions/35372499/how-can-i-delete-rows-for-a-particular-date-in-a-pandas-dataframe