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

如何在R中基于含行名的DataFrame按Individual ID求平均合并matrix行?

Python解决方案:按Individual ID合并矩阵行并求均值

实现步骤

直接通过pandas完成映射、分组、均值计算,步骤简洁可复用:

  1. 导入依赖库
import pandas as pd
import numpy as np
  1. 构造示例数据(替换为你的真实数据即可)
# 带行名的目标矩阵
matrix = np.array([[10, 20, 30],
                   [15, 25, 35],
                   [40, 50, 60]])
row_names = ['A', 'B', 'C']

# 样本与个体ID映射表
sample_df = pd.DataFrame({
    'sampleid': ['A', 'B', 'C'],
    'Individual ID': [1, 1, 2]
})
  1. 将矩阵转为带行名的DataFrame
matrix_df = pd.DataFrame(matrix, index=row_names)
  1. 对齐映射关系与矩阵数据
# 将映射表的行名设为sampleid,方便和矩阵行名匹配
sample_df = sample_df.set_index('sampleid')
# 合并矩阵数据与个体ID信息
merged_df = matrix_df.join(sample_df)
  1. 按Individual ID分组求均值
# 对同一ID下的所有数值列计算平均值
result_df = merged_df.groupby('Individual ID').mean()
  1. (可选)转回numpy矩阵格式
    如果需要得到最终的矩阵结果:
result_matrix = result_df.to_numpy()
# 对应的行名是Individual ID列表
result_row_names = result_df.index.tolist()

输出结果示例

运行代码后,result_df会输出:

0     1     2
Individual ID                
1              12.5  22.5  32.5
2              40.0  50.0  60.0

其中ID为1的行是原A、B两行的平均值,ID为2的行保留原C行的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:42:42