在Pandas中获取数据帧子集

2024-06-02 19:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧data

    maturity    spot rate
0   1Y  0.182
1   2Y  0.20199999999999999
2   3Y  0.284
3   4Y  0.426
4   5Y  0.585
5   6Y  0.745
6   7Y  0.892
7   8Y  1.021
8   9Y  1.13
9   10Y 1.224
10  12Y 1.375
11  15Y 1.5219999999999998
12  20Y 1.653
13  25Y 1.7109999999999999
14  30Y 1.739

我有一行代码,允许我提取到某个成熟度(max maturity是我给出的输入):

data = data.iloc[:data.loc[data.maturity.str.contains(max_maturity,na=False)].index[0]]

然而,问题是,如果我想达到20Y,并把max_maturity作为20Y,那么它只能达到15Y。是否有一种方法可以提取20Y行之前(包括20Y行)的所有行


Tags: 数据代码falsedataindexratelocmax
3条回答

您可以将maturity列与max_maturity进行比较以创建布尔掩码,然后反转此掩码并使用累积最大值创建生成的布尔掩码,该掩码可用于过滤所需行:

max_maturity = '20Y'
df.loc[df['maturity'].eq(max_maturity)[::-1].cummax()]

   maturity  spot rate
0        1Y      0.182
1        2Y      0.202
2        3Y      0.284
3        4Y      0.426
4        5Y      0.585
5        6Y      0.745
6        7Y      0.892
7        8Y      1.021
8        9Y      1.130
9       10Y      1.224
10      12Y      1.375
11      15Y      1.522
12      20Y      1.653

一个想法是只比较数字,因此可以使用<=

max_maturity = '20Y'
#if need extract 20
max_maturity = int(''.join(filter(str.isdigit, max_maturity)))

max_maturity = 20
#remove Y
df = df[df['maturity'].str.replace('Y','').astype(int) <= max_maturity]
#get numbers only
#df = df[df['maturity'].str.extract('(\d+)', expand=False).astype(int) <= max_maturity]

print (df)
   maturity  spot rate
0        1Y      0.182
1        2Y      0.202
2        3Y      0.284
3        4Y      0.426
4        5Y      0.585
5        6Y      0.745
6        7Y      0.892
7        8Y      1.021
8        9Y      1.130
9       10Y      1.224
10      12Y      1.375
11      15Y      1.522
12      20Y      1.653

使用^{}移位掩码的解决方案:

idx = data.index[data.maturity.str.contains(max_maturity,na=False).shift(fill_value=False)]

data = data.iloc[: idx[0]]

如果列maturity中的元素属于类型str,则可以将它们作为字符串进行比较,因为它们的末尾都有“Y”。我将按如下方式过滤数据帧:

data = data[data.maturity<='max_maturity']

相关问题 更多 >