简体   繁体   English

在日期索引的 dataframe 中向上移动 x 行

[英]Moving x rows up in a dataframe indexed on dates

I have a dataframe that has Date as its index .我有一个以Date 作为索引的 dataframe 。 The dataframe has stock market related data so the dates are not continuous. dataframe 有股市相关数据,因此日期不连续。 If I want to move lets say 120 rows up in the dataframe, how do I do that.如果我想在 dataframe 中移动 120 行,我该怎么做。 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:如果我想从 2018 年初之前的 120 个交易日开始获取数据,我该怎么做:

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:假设您使用的是 pandas 并且 dataframe 按日期排序,一个非常简单的方法是:

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.上面df.columns.get_loc('2018')将给出 numpy 切片 object 并将为我们提供 2018 年第一个元素的索引(我们使用切片的.start属性对其进行索引),类似地我们对 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:现在考虑您想要 2018 年前 6 个月的数据(不知道第一天是哪一天),同样可以使用:

>>> 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.正如您在上面看到的,我们使用相同的逻辑对 2018 年的前 6 个月进行了索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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