pandas - 按最大值作为索引对数据帧进行切片

标签 pandas dataframe slice

我目前有一个应变应力的数据框,包含相应的值。我想以特定方式对数据帧进行切片 - 我想找到压力中的最大值,然后获取数据帧的接下来 5 行。 (我不想只找到列中的所有最高值并按其排序。)这是我当前正在做的事情:

import pandas as pd

df = pd.DataFrame({"strain": [1,2,4,6,2,4,7,4,8,3,4,7,3,3,6,4,7,4,3,2],
                    "stress": [0,0.2,0.5,0.8,0.7,1,0.7,0.6,0.7,0.8,0.4,0.2,0,-0.5,-0.8,-1,-0.8,-0.9,-0.7,-0.6]})

#Sort by stress values
new_df = df.copy()

new_df = new_df.sort_values(by = ['stress'], ascending = False)

new_df = new_df[0:5]

这是我当前的输出:

print(new_df)

   strain  stress
5       4     1.0
3       6     0.8
9       3     0.8
4       2     0.7
6       7     0.7

所以我的代码是按压力的最高值排序的。但是,我想将行顺序保持在列中最高值后面。这将是我的预期输出:

print(new_df)

strain  stress
5        4     1.0
6        7     0.7
7        4     0.6
8        8     0.7
9        3     0.8

最佳答案

您可以使用argmax找到最大值的索引:

imax = df.stress.argmax()
df.iloc[imax:imax+5]

结果:

   strain  stress
5       4     1.0
6       7     0.7
7       4     0.6
8       8     0.7
9       3     0.8

关于pandas - 按最大值作为索引对数据帧进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73079091/

相关文章:

python - 失败 : Replace a single value with a new value for an individual DataFrame column

arrays - Go 如何保证元素指针对数组和 slice 有效?

python - Pandas 在中间行上移动列中的值

python - Pandas read_excel 干扰 na_values 和转换器错误?

python - DataFrame 运行计数和连接

python - 如何组合两列的浮点值并将其放入数据帧的另一列中?

arrays - 如何将 slice 转换为数组?

go - Reflection.DeepEqual()返回false但 slice 相同

Python 使用 Pandas/Urllib 下载文件

python - Pandas 从 python 中的日期字符串列获取日期值