简体   繁体   中英

Moving x rows up in a dataframe indexed on dates

I have a dataframe that has Date as its index . The dataframe has stock market related data so the dates are not continuous. If I want to move lets say 120 rows up in the dataframe, how do I do that. For example:

If I want to get the data starting from 120 trading days before the start of yr 2018, how do I do that below:

df['2018-01-01':'2019-12-31']

Thanks

Assuming you are using pandas and the dataframe is sorted by dates, a very simple way would be:

initial_date = '2018-01-01'

initial_date_index = df.loc[df['dates']==initial_date].index[0]

offset=120

start_index = initial_date_index-offset


new_df = df.loc[start_index:]

Try this:

df[df.columns[df.columns.get_loc('2018-01-01'):df.columns.get_loc('2019-12-31')]]

Get location of both Columns in the column array and index them to get the desired.

UPDATE:

Based on your requirement, make some little modifications of above.

Yearly Indexing

>>> df[df.columns[(df.columns.get_loc('2018')).start:(df.columns.get_loc('2019')).stop]]

Above df.columns.get_loc('2018') will give out numpy slice object and will give us index of first element of 2018 (which we index using .start attribute of slice) and similarly we do for index of last element of 2019.

Monthly Indexing

Now consider you want data for First 6 months of 2018 (without knowing what is the first day), the same can be done using:

>>> df[df.columns[(df.columns.get_loc('2018-01')).start:(df.columns.get_loc('2018-06')).stop]]

As you can see above we have indexed the first 6 months of 2018 using the same logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM