首页 > 解决方案 > 在 Pandas 中获取数据框的子集

问题描述

我有一个数据框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 行?

标签: pythonpandasdataframe

解决方案


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

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

您使用移位掩码的解决方案Series.shift

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

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

推荐阅读