我有一个数据框数据
:
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
我有一行代码,允许我提取直到某个成熟度(最大成熟度
是我给出的输入):
data = data.iloc[:data.loc[data.maturity.str.contains(max_maturity,na=False)].index[0]]
但是问题是,如果我想达到 20 年,并将 max_maturity
设置为 20 年,则最多只能达到 15 年。有没有办法提取 20Y 行之前的所有行(包括 20Y 行)?
最佳答案
一个想法是仅比较数字,因此可以使用 <=
:
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]]
关于python - 获取 Pandas 中数据帧的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66673789/