计算多个列并在单独的列中列出计数并保留一列

Counting multiples columns and list the counts in separate columns and retain a column

我有以下数据框:

    id  coord_id    val1    val2    record  val3
0   snp chr15_1-1000    1.0 0.9 xx12    2
1   snv chr15_1-1000    1.0 0.7 yy12    -4
2   ins chr15_1-1000    0.01    0.7 jj12    -4
3   ins chr15_1-1000    1.0 1.5 zzy1    -5
4   ins chr15_1-1000    1.0 1.5 zzy1    -5
5   del chr10_2000-4000 0.1 1.2 j112    12
6   del chr10_2000-4000 0.4 1.1 jh12    15

我正在尝试计算每个 coord_id 出现在每个 id 中的次数,但将 val1 列保留在结果 table 中,但只包含该列中的值范围所以例如,我正在尝试完成以下结果:

  id            snp    snv         ins    del   total val1  
chr15_1-1000    1       1           3      0     5     0.01-1.0
chr10_2000-4000 0       0           0      2     2    0.1-0.4

我想按列总数升序排列。

非常感谢。

首先使用计数聚合和保证金总和转入 id 列。然后 join()val1 最小-最大字符串:

(df.pivot_table(index='coord_id', columns='id', values='val1',
                aggfunc='count', fill_value=0,
                margins=True, margins_name='total')
   .join(df.groupby('coord_id').val1.agg(lambda x: f'{x.min()}-{x.max()}'))
   .sort_values('total', ascending=False)
   .drop('total'))

#                  del  ins  snp  snv  total      val1
# coord_id                                            
# chr15_1-1000       0    3    1    1      5  0.01-1.0
# chr10_2000-4000    2    0    0    0      2   0.1-0.4

我建议分别进行两次计算——获取范围和计算频率。

temp = test_df.groupby(['coord_id']).agg({'val1': ['min', 'max']})
temp.columns = temp.columns.get_level_values(1)
temp['val1'] = temp['min'].astype(str) + '-' + temp['max'].astype(str)

然后,

temp2 = test_df.groupby(['coord_id', 'id']).count().unstack('id').fillna(0)
temp2.columns = temp2.columns.get_level_values(1)

最后,合并

answer = pd.concat([temp, temp2], axis=1)