python - 获取 Pandas 中数据帧的子集

标签 python pandas dataframe

我有一个数据框数据:

    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/

相关文章:

python - 我无法在 python 3.8 中使用tensorflow

python - 在 Python 中使用模拟测试派生类

python - Pandas:在变量列表上使用条件 df[variable].isnull 创建新列

python - 如何为每个索引值添加差异行?

python - 对某些列执行 groupby.sum,对其他列执行 groupby.mean

python - python中的多线程文件下载并在shell中更新下载进度

python - 如何让 pytest 等待(手动)用户操作?

python - 删除数据框中的重复元素python

hadoop - Apache Spark : Which data storage and data format to choose

r - 在 dplyr 中使用管道时处理空数据帧(<0 rows>)