这是我的DataFrame:

import pandas as pd
df = pd.DataFrame(
    {
        'a': ['x', 'x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'y', 'y', 'y'],
        'b': [1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2],
        'c': [9, 8, 11, 13, 14, 3, 104, 106, 11, 100, 70, 7]
    }
)

预期输出:创建列out:

    a  b    c    out
0   x  1    9    NaN
1   x  1    8    NaN
2   x  1   11    NaN
3   x  2   13  found
4   x  2   14    NaN
5   y  1    3    NaN
6   y  1  104  found
7   y  1  106    NaN
8   y  2   11    NaN
9   y  2  100    NaN
10  y  2   70    NaN
11  y  2    7    NaN

面具是:

mask = (df.c > 10)

过程:收件箱是通过第a列:

a)对于每个组,找到满足mask条件的第一行.

b)对于组x,此条件仅适用于b == 2.这就是 Select 第3行的原因.

这是我的try .它已经接近了,但感觉不是这样:

def func(g):
    mask = (g.c > 10)
    g.loc[mask.cumsum().eq(1) & mask, 'out'] = 'found'
    return g

df = df.groupby('a').apply(func)

推荐答案

有一个选项groupby.idxmax:

mask = (df['c'] > 10) & (df['a'].ne('x') | df['b'].eq(2))

idx = mask.groupby(df['a']).idxmax()
df.loc[idx[mask.loc[idx].values], 'out'] = 'found'

另一个有groupby.transform:

mask = (df['c'] > 10) & (df['a'].ne('x') | df['b'].eq(2))

df.loc[mask & mask.groupby(df['a'])
                  .transform(lambda m: (~m).shift(fill_value=True)
                                           .cummin()),
       'out'] = 'found'

输出,带有没有匹配项的额外组z:

    a  b    c    out
0   x  1    9    NaN
1   x  1    8    NaN
2   x  1   11    NaN
3   x  2   13  found
4   x  2   14    NaN
5   y  1    3    NaN
6   y  1  104  found
7   y  1  106    NaN
8   y  2   11    NaN
9   y  2  100    NaN
10  y  2   70    NaN
11  y  2    7    NaN
12  z  3    1    NaN
13  z  3    1    NaN

last match

要获取最后一个匹配项(而不是第一个),只需反转面具即可:

示例:

mask = (df['c'] > 10) & (df['a'].ne('x') | df['b'].eq(2))

mask = mask[::-1]

idx = mask.groupby(df['a']).idxmax()
df.loc[idx[mask.loc[idx].values], 'out'] = 'found'

    a  b    c    out
0   x  1    9    NaN
1   x  1    8    NaN
2   x  1   11    NaN
3   x  2   13    NaN
4   x  2   14  found
5   y  1    3    NaN
6   y  1  104    NaN
7   y  1  106    NaN
8   y  2   11    NaN
9   y  2  100    NaN
10  y  2   70  found
11  y  2    7    NaN
12  z  3    1    NaN
13  z  3    1    NaN

Python相关问答推荐

如何用symy更新分段函数

无法使用equals_html从网址获取全文

Python中使用时区感知日期时间对象进行时间算术的Incredit

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

具有多个选项的计数_匹配

如何自动抓取以下CSV

使用miniconda创建环境的问题

两个pandas的平均值按元素的结果串接元素.为什么?

Python+线程\TrocessPoolExecutor

为什么\b在这个正则表达式中不解释为反斜杠

使用Openpyxl从Excel中的折线图更改图表样式

从旋转的DF查询非NaN值

如何按row_id/row_number过滤数据帧

当HTTP 201响应包含 Big Data 的POST请求时,应该是什么?  

为什么dict. items()可以快速查找?

Pandas:将值从一列移动到适当的列

对于数组中的所有元素,Pandas SELECT行都具有值

按列表分组到新列中

如何在Polars中将列表中的新列添加到现有的数据帧中?

#将多条一维曲线计算成其二维数组(图像)表示