根据标签索引获取数据帧的子集

时间:2021-05-03 07:32:09

标签: python python-3.x pandas dataframe data-science

我有一个来自雅虎财经的数据框

import pandas as pd
import yfinance
ticker = yfinance.Ticker("INFY.NS")
df = ticker.history(period = '1y')
print(df)

这给了我 df as,

enter image description here

如果我指定,

date = "2021-04-23"
  • 我需要一个 df 子集,其行的索引标签为“2021-04-23”
  • 日期前 2 天的行
  • 日期后 1 天的行

这里重要的是,我们无法在使用日期字符串之前和之后进行计算,因为 df 可能没有一些日期,但要根据索引打印行。 (即 2 行前一个索引和一行下一个索引) 例如,在df中,没有“2021-04-21”而是“2021-04-20”

我们如何实现这一点?

2 个答案:

答案 0 :(得分:2)

如果需要位置前后的值(如果在date中始终存在DatetimeIndex)使用DataFrame.iloc,位置由Index.get_locmin和{{ 1}} 用于选择行,如果在 max 之前或 2 之后不存在值,如示例数据:

1

注意: 添加 df = pd.DataFrame({'a':[1,2,3]}, index=pd.to_datetime(['2021-04-21','2021-04-23','2021-04-25'])) date = "2021-04-23" pos = df.index.get_loc(date) df = df.iloc[max(0, pos-2):min(len(df), pos+2)] print (df) a 2021-04-21 1 2021-04-23 2 2021-04-25 3 min 用于选择日期是第一个(之前不存在 2 个值,或第二个 - 之前不存在第二个值)还是最后一个(之后不存在值)< /p>

答案 1 :(得分:2)

您可以使用基于整数的索引。首先找到所需的 date 的整数位置,然后使用 iloc 取所需的子集:

def get_subset(df, date):
    # get the integer index of the matching date(s)
    matching_dates_inds, = np.nonzero(df.index == date)
    
    # and take the first one (works in case of duplicates)
    first_matching_date_ind = matching_dates_inds[0]
    
    # take the 4-element subset
    desired_subset = df.iloc[first_matching_date_ind - 2: first_matching_date_ind + 2]

    return desired_subset
相关问题