python - 在 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 行?
解决方案
一个想法是仅比较数字,因此可能使用<=
:
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]]
推荐阅读
- javascript - CSS 不适用于标签,write() 方法包含在函数内部
- excel - 如何使用偏移函数在excel中获取不同数据集的斜率?
- c++ - 高斯模糊缩小缩放图像?
- django - 无法在 django 视图中使用 PUT Ajax 请求接收数据值
- c# - Swagger Swashbuckle 路线阻塞
- python - DBSCAN kdist-绘制多个山谷
- c++ - 流行的 vscode #include iostream 错误
- python - Python:按创建日期或文件名中的数字列出目录中的XML文件
- python - discord.py 和 youtube_dl,“读取错误”和“会话因某种原因已失效”
- python - Python ASCII 绘图仪