Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas select rows by list of dates

How to select multiple rows of a dataframe by list of dates

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))

In[1]: df

Out[1]: 
                   A         B         C         D
2013-01-01  0.084393 -2.460860 -0.118468  0.543618
2013-01-02 -0.024358 -1.012406 -0.222457  1.906462
2013-01-03 -0.305999 -0.858261  0.320587  0.302837
2013-01-04  0.527321  0.425767 -0.994142  0.556027
2013-01-05  0.411410 -1.810460 -1.172034 -1.142847
2013-01-06 -0.969854  0.469045 -0.042532  0.699582

myDates = ["2013-01-02", "2013-01-04", "2013-01-06"]

So the output should be

                   A         B         C         D
2013-01-02 -0.024358 -1.012406 -0.222457  1.906462
2013-01-04  0.527321  0.425767 -0.994142  0.556027
2013-01-06 -0.969854  0.469045 -0.042532  0.699582
like image 993
Pat Avatar asked Nov 01 '16 15:11

Pat


People also ask

How do I select a specific date range in pandas?

In order to select rows between two dates in pandas DataFrame, first, create a boolean mask using mask = (df['InsertedDates'] > start_date) & (df['InsertedDates'] <= end_date) to represent the start and end of the date range. Then you select the DataFrame that lies within the range using the DataFrame. loc[] method.

How do I filter data frames between two dates?

There are two possible solutions: Use a boolean mask, then use df. loc[mask] Set the date column as a DatetimeIndex, then use df[start_date : end_date]

How do I filter out rows in pandas DataFrame?

You can use df[df["Courses"] == 'Spark'] to filter rows by a condition in pandas DataFrame. Not that this expression returns a new DataFrame with selected rows. You can also write the above statement with a variable.


1 Answers

You can use index.isin() method to create a logical index for subsetting:

df[df.index.isin(myDates)]

enter image description here

like image 182
Psidom Avatar answered Sep 18 '22 18:09

Psidom