You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas按正则筛选列计算DataFrame每行指定列区间的均值?

解决指定列区间的行均值计算问题

原始数据与需求

原始DataFrame:

id  weight  Project   Exp_type   researcher events_d1 events_d2 events_d3 events_d4  events_d5   
0   50        p1        Acute      alex         0         0         0         4       2
1   52        p2        chronic    mat          0         1         1         5       1
2   75        p1        Acute      alex         1                   2                 1
3   53        p2        chronic    mat          0                             0       0

需求:为每行计算events_d2到events_d4这三列的均值,生成新列meand2_d4,均值计算固定以3为分母(空值视为0),最终结果示例如下:

weight  Project Exp_type   researcher events_d1 events_d2 events_d3 events_d4  events_d5  meand2_d4 
0 50      p1      Acute      alex         0         0         0         4          2          1.33
1 52      p2      chronic    mat          0         1         1         5          1          2.33
2 75      p1      Acute      alex         1                   2                    1          0.66
3 53      p2      chronic    mat          0                             0          0          0

原代码问题分析

你尝试的代码df['meand2_d4'] = df.filter(regex="events_d[2-4]").agg(np.mean, axis=1)存在两个问题:

  1. 分母不固定:np.mean默认会跳过空值/NaN,用非空值的数量作为分母,导致每行均值的计算标准不一致;
  2. 可能列筛选异常:如果原始数据中的空值是字符串格式而非NaN,或者列名存在格式问题,可能导致filter没有正确锁定目标列,进而计算了整行的均值。

正确解决方案

核心思路:先将目标列的空值统一转为0,再以固定列数(3)为分母计算均值。

完整代码

import pandas as pd

# 构造原始DataFrame(模拟空值为字符串的情况)
data = {
    'id': [0, 1, 2, 3],
    'weight': [50, 52, 75, 53],
    'Project': ['p1', 'p2', 'p1', 'p2'],
    'Exp_type': ['Acute', 'chronic', 'Acute', 'chronic'],
    'researcher': ['alex', 'mat', 'alex', 'mat'],
    'events_d1': [0, 0, 1, 0],
    'events_d2': [0, 1, '', ''],
    'events_d3': [0, 1, 2, ''],
    'events_d4': [4, 5, '', 0],
    'events_d5': [2, 1, 1, 0]
}
df = pd.DataFrame(data)

# 1. 筛选目标列(events_d2到events_d4)
target_cols = df.filter(regex="events_d[2-4]").columns

# 2. 将目标列的空字符串、非数值转为0
df[target_cols] = df[target_cols].replace('', 0).apply(pd.to_numeric, errors='coerce').fillna(0)

# 3. 计算固定分母的均值,保留两位小数
df['meand2_d4'] = (df[target_cols].sum(axis=1) / 3).round(2)

# 输出去掉id列的结果(匹配示例格式)
print(df.drop('id', axis=1))

运行结果

weight Project Exp_type researcher  events_d1  events_d2  events_d3  events_d4  events_d5  meand2_d4
0      50      p1    Acute       alex          0        0.0        0.0        4.0          2       1.33
1      52      p2  chronic        mat          0        1.0        1.0        5.0          1       2.33
2      75      p1    Acute       alex          1        0.0        2.0        0.0          1       0.67
3      53      p2  chronic        mat          0        0.0        0.0        0.0          0       0.00

(注:第2行的0.67是四舍五入结果,若需0.66可改为(sum / 3).apply(lambda x: "{:.2f}".format(x))格式化)

内容的提问来源于stack exchange,提问作者Pietro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 19:04:52