python - 使用 groupby 和 mean() 在 Pandas 中保留一个带有分类变量的列

标签 python pandas pandas-groupby categorical-data

有没有办法在 groupbymean() 之后保留分类变量? 例如,给定数据框 df:

              ratio    Metadata_A      Metadata_B   treatment
0      54265.937500           B10               1  AB_cmpd_01
11    107364.750000           B10               2  AB_cmpd_01
22     95766.500000           B10               3  AB_cmpd_01
24     64346.250000           B10               4  AB_cmpd_01
25     52726.333333           B10               5  AB_cmpd_01
30     65056.600000           B11               1          UT
41     78409.600000           B11               2          UT
52    133533.000000           B11               3          UT
54    102433.571429           B11               4          UT
55     82217.588235           B11               5          UT
60     89843.600000            B2               1          UT
71     98544.000000            B2               2          UT
82    179330.000000            B2               3          UT
84    107132.400000            B2               4          UT
85     73096.909091            B2               5          UT

我需要对每个 Metadata_A 中的 ratio 进行平均,但最后要保留 treatment 列:

理论上是这样的:

df.groupby(by='Metadata_A').mean().reset_index()

              ratio    Metadata_A      Metadata_B   treatment
 0     54265.937500           B10             2.5  AB_cmpd_01
 1     78409.600000           B11             2.5          UT
 2    107132.400000            B2             2.5          UT

但是,treatment 列在平均后消失了。

最佳答案

您可以将 groupbyagg 一起使用

df.groupby(['Metadata_A','treatment'],as_index=False).agg({'Metadata_B':'mean','ratio':'first'})
Out[358]: 
  Metadata_A   treatment  Metadata_B       ratio
0        B10  AB_cmpd_01           3  54265.9375
1        B11          UT           3  65056.6000
2         B2          UT           3  89843.6000

关于python - 使用 groupby 和 mean() 在 Pandas 中保留一个带有分类变量的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50052570/

相关文章:

python - 在python中下载文件并取消

python - 如何使用 Boto3 get_query_results 方法从 AWS Athena 创建 Dataframe

pandas - 确保 Pandas MultiIndex 中的字典序排序

python - 在 Pandas 中使用 groupby 将一列中的内容与另一列进行比较

python - 如何循环遍历 pandas 分组时间序列?

python - 将实时音频数据读入 numpy 数组

python - 如何从内存中解码jpg图像?

python - 使用 Docker 时套接字 IO 响应缓慢

python - Groupby 多级索引中的时间仓

python - 如何在 python 中的这个 pandas 数据框中使用 groupby 或 pivot