python - 查找每行中最后一列匹配模式

标签 python regex pandas

我有一个包含几列“操作”的数据框。如何找到与模式匹配的最后一个操作并返回其列索引或标签?

我的数据:

name    action_1    action_2    action_3
bill    referred    referred    
bob     introduced  referred    referred
mary    introduced      
june    introduced  referred    
dale    referred        
donna   introduced

我想要什么:

name    action_1    action_2    action_3    last_referred
bill    referred    referred                action_2
bob     introduced  referred    referred    action_3
mary    introduced                          NA
june    introduced  referred                action_2
dale    referred                            action_1
donna   introduced                          NA

最佳答案

只需沿 axis=1 使用 apply 函数,并将 pattern 参数作为附加参数传递给该函数。

In [3]: def func(row, pattern):
            referrer = np.nan
            for key in row.index:
                if row[key] == pattern:
                    referrer = key
            return referrer
        df['last_referred'] = df.apply(func, pattern='referred', axis=1)
        df
Out[3]:     name    action_1  action_2  action_3 last_referred
        0   bill    referred  referred      None      action_2
        1    bob  introduced  referred  referred      action_3
        2   mary  introduced                               NaN
        3   june  introduced  referred                action_2
        4   dale    referred                          action_1
        5  donna  introduced                               NaN

关于python - 查找每行中最后一列匹配模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18540563/

相关文章:

python - 有可用的 python OpenID 服务器吗?

python - 应用程序错误日志在哪里?

python - 如何在 pandas DataFrame 中查找与正则表达式匹配的实际唯一值

javascript - 使用 Javascript 验证正则表达式

python - 进行 groupby 时保留其他列

python - 为什么 pandas read_csv 没有读取正确的行数?

python - pd.rolling_mean 已弃用 - ndarrays 的替代品

java - Python 和 Java 中相同正则表达式的不同行为

python - 如何提取值(value)

python - 如何更改xlabel的pandas DataFrame.plot fontsize?