例如,我有一个这样的数据帧

   Value   Placement
0    12      high
1    15      high
2    18      high
3    14      high
4    4       low
5    5       low
6    9       high
7    11      high
8    2       low
9    1       low
10   3       low
11   2       low

我想创建第二个框架,其中包含"Value"列中的最高值(对于具有"high"放置的每组连续行)和"Value"列中的最低值(对于具有"low"放置的每组连续行).比如说

   Value   Placement
0    18      high
1    4       low
2    11      high
3    1       low

我也不想更改行的顺序,因为"高"和"低"的顺序对项目的功能至关重要.

我可以只迭代原始的数据帧并跟踪"Value"中的数字,直到检测到"Placement"中的更改,但我听说数据帧迭代非常慢,如果可能的话,应该避免.有什么方法可以在不迭代的情况下做到这一点吗?提亚

推荐答案

按连续值分组,将符号替换为与"Low"匹配的Placement,并获得每组idxmax,然后将选定行保留为loc:

# group consecutive rows
group = df['Placement'].ne(df['Placement'].shift()).cumsum()

# invert the low values, get idxmax per group
keep = (df['Value']
        .mul(df['Placement'].map({'low': -1, 'high': 1}))
        .groupby(group, sort=False).idxmax()
        )

out = df.loc[keep]

如果效率是个问题,而且由于groupby基于的是一个Python循环,那么另一种方法(对于许多组来说可能更快)将是稳定的--按值和组(使用numpy.lexsort)对行进行排序,并使用drop_duplicates(在符号交换为"low"之后)保持最高值:

group = df['Placement'].ne(df['Placement'].shift()).cumsum()
s = df['Value'].mul(df['Placement'].map({'low': -1, 'high': 1}))

keep = (group
        .iloc[np.lexsort([s, group])]
        .drop_duplicates(keep='last')
        .index
        )

out = df.loc[keep]

Note that despite the sorting step, this strategy will maintain the relative original order of the rows.

输出:

   Value Placement
2     18      high
4      4       low
7     11      high
9      1       low

时间比较:

enter image description here

Python相关问答推荐

Pandas基于另一列的价值的新列

在有限数量的唯一字母的长字符串中,找到包含重复不超过k次的所有唯一字母的最长子字符串

在Python中,如何才能/应该使用decorator 来实现函数多态性?

是否有方法将现有的X-Y图转换为X-Y-Y1图(以重新填充)?

如何将Matplotlib的fig.add_axes本地坐标与我的坐标关联起来?

使用matplotlib pcolormesh,如何停止从一行绘制的磁贴连接到上下行?

NumPy中的右矩阵划分,还有比NP.linalg.inv()更好的方法吗?

无法使用python.h文件; Python嵌入错误

Python中的负前瞻性regex遇到麻烦

根据给定日期的状态过滤查询集

如何才能知道Python中2列表中的巧合.顺序很重要,但当1个失败时,其余的不应该失败或是0巧合

将特定列信息移动到当前行下的新行

为什么这个带有List输入的简单numba函数这么慢

如何在虚拟Python环境中运行Python程序?

基于索引值的Pandas DataFrame条件填充

启动带有参数的Python NTFS会导致文件路径混乱

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

寻找Regex模式返回与我当前函数类似的结果

(Python/Pandas)基于列中非缺失值的子集DataFrame