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

如何在Pandas DataFrame中合并多行并按需求生成单行结果?

解决Pandas DataFrame三行合并为单行的问题

核心思路

不用sum()函数(会因NaN导致结果异常),而是按优先级规则逐列赋值:

  1. 优先保留Zero行的0
  2. 其次将Miss行的数值转为NaN(即null)
  3. 最后将Max行的浮点数转为整数作为默认值

具体步骤

1. 预处理数据:替换连字符为缺失值

先把DataFrame中的-.----统一替换为Pandas的缺失值pd.NA:

import pandas as pd
import numpy as np

# 假设你的原始DataFrame为df
df = df.replace('-.----', pd.NA)

2. 提取三行数据

分别取出Max、Zero、Miss三行单独处理:

max_row = df.loc['MaxST1 - ST2-V']
zero_row = df.loc['ZeroST1 - ST2-V']
miss_row = df.loc['MissST1 - ST2-V']

3. 处理Miss行:将数值转为NaN

把Miss行中所有非缺失的数值统一转为NaN:

# 无论Miss行原数值是什么,都转为NaN
miss_row = miss_row.apply(lambda x: pd.NA if pd.notna(x) else pd.NA)

4. 按优先级合并为单行

用np.select实现多条件判断,生成最终结果行:

# 定义判断条件
conditions = [
    zero_row == 0,          # 条件1:Zero行是0
    pd.notna(miss_row)      # 条件2:Miss行需转为null
]

# 对应条件的取值
choices = [
    0,                      # 满足条件1时取0
    pd.NA                   # 满足条件2时取null
]

# 不满足上述条件时,取Max行浮点数四舍五入为整数
result_row = np.select(conditions, choices, default=max_row.round().astype(int))

# 转为Series并重命名行(替换为你的受试者编号)
result_series = pd.Series(result_row, index=df.columns, name='受试者_001')

# 若需要转为DataFrame格式
result_df = result_series.to_frame().T

关键说明

  • 浮点数转整数:示例用round().astype(int)做四舍五入,若需直接截断小数部分,可改为astype(int);如需向上/向下取整,用np.ceil(max_row).astype(int)或np.floor(max_row).astype(int)
  • 优先级逻辑:确保Zero行的0不会被其他值覆盖,Miss行标记的null优先于Max行的数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:02:03