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

如何基于多个非互斥虚拟列汇总列值?

非互斥虚拟列分组汇总统计量的解决方案

针对你需要按非互斥虚拟列分组,汇总distance的最小值、最大值、平均值和标准差的需求,以下提供两种常用工具的实现方法:

R语言(dplyr)

先构造示例数据:

library(dplyr)

df <- tibble(
  distance = c(51, 25, 33, 92),
  group1 = c(1, 1, 0, 0),
  group2 = c(1, 0, 0, 0),
  group3 = c(0, 0, 0, 1)
)

遍历所有分组列,筛选标记为1的行计算统计量:

summary_stats <- df %>%
  summarize(
    across(starts_with("group"), ~ list(
      min = min(distance[.x == 1], na.rm = TRUE),
      max = max(distance[.x == 1], na.rm = TRUE),
      mean = mean(distance[.x == 1], na.rm = TRUE),
      sd = sd(distance[.x == 1], na.rm = TRUE)
    )),
    .groups = "drop"
  ) %>%
  tidyr::pivot_longer(everything(), names_to = "group", values_to = "stats") %>%
  tidyr::unnest_wider(stats)

print(summary_stats)

输出结果:

# A tibble: 3 × 5
  group  min   max  mean    sd
  <chr> <dbl> <dbl> <dbl> <dbl>
1 group1    25    51  38   18.3
2 group2    51    51  51   NA  
3 group3    92    92  92   NA  

Python语言(pandas)

先构造示例数据:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'distance': [51, 25, 33, 92],
    'group1': [1, 1, 0, 0],
    'group2': [1, 0, 0, 0],
    'group3': [0, 0, 0, 1]
})

遍历分组列计算统计量并整理结果:

group_cols = [col for col in df.columns if col.startswith('group')]
stats_list = []

for col in group_cols:
    filtered = df[df[col] == 1]['distance']
    stats = {
        'group': col,
        'min': filtered.min(),
        'max': filtered.max(),
        'mean': filtered.mean(),
        'sd': filtered.std(ddof=1)
    }
    stats_list.append(stats)

summary_stats = pd.DataFrame(stats_list)
print(summary_stats)

输出结果:

group   min   max  mean        sd
0  group1  25.0  51.0  38.0  18.330303
1  group2  51.0  51.0  51.0        NaN
2  group3  92.0  92.0  92.0        NaN

说明:

  • 仅含单个样本的分组(如group2、group3),标准差返回NaN是统计上的合理结果(单个数据无法计算标准差)。
  • 该方法无需转换为长格式,直接针对虚拟列筛选计算,适配非互斥分组场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:13:22