gpt4 book ai didi

python - 聚合值与 pandas 中的相应计数

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:45 24 4
gpt4 key购买 nike

我有像这样的 Pandas 数据框:

my_df = 

chr PI
2 5
2 5
2 5
2 6
2 6
2 8
2 8
2 8
2 8
2 8
3 5
3 5
3 5
3 5
3 9
3 9
3 9
3 9
3 9
3 9
3 9
3 7
3 7
3 4
......
......

我想将它转换成新的数据框,其中包含有关数据框的新信息,例如:

  • chr:独特的染色体
  • unq_PI :每条染色体内唯一 PI 的数量
  • PIs:该染色体中“PI”值的列表
  • PI_freq:相应染色体中每个“PI”的长度

因此,预期输出为:

chr   unq_PI   PIs        PI_freq
2 3 5,6,8 3,2,5
3 4 5,9,7,4 4,7,2,1

我在想:

new_df = pd.DataFrame({'chr': my_df['chr'].unique(),
'unq_PI': my_df('chr')['unq_PI'].nunique()),
'PIs': .......................,
'PI_freq': ..................})

The only code that works is for `chr` when used alone; any additional code just throws an error. How can I fix this?

最佳答案

使用groupby + value_counts,然后是groupby + agg

v = (df.groupby('chr')
.PI
.apply(pd.Series.value_counts, sort=False)
.reset_index(level=1)
.astype(str)
.groupby(level=0)
.agg(','.join)
.rename(columns={'level_1' : 'PIs', 'PI' : 'PI_freq'})
)

这不考虑唯一值的计数,可以使用 groupby + nunique 计算:

v.insert(0, 'unq_PI', df.groupby('chr').PI.nunique())

v 

unq_PI PIs PI_freq
chr
2 3 5,6,8 3,2,5
3 4 4,5,7,9 1,4,2,7

关于python - 聚合值与 pandas 中的相应计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com