Python:在数据集中计算每个组的第2和第3四分位数。

huangapple go评论86阅读模式
英文:

Python: calculating the 2 and 3 quartiles per group in a dataset

问题

我有以下的数据框:

  1. df =
  2. code count
  3. A 1
  4. A 2
  5. A 3
  6. A 4
  7. B 7
  8. B 8
  9. B 9
  10. B 10

我想要为每个代码生成第25和第75百分位数:

  1. code 25QT 75QT
  2. A 2.5 3.5
  3. B 8.5 9.5
英文:

I have the following dataframe:

  1. df =
  2. code count
  3. A 1
  4. A 2
  5. A 3
  6. A 4
  7. B 7
  8. B 8
  9. B 9
  10. B 10

I want to produce the 25 and 75 quartiles per code:

  1. code 25QT 75QT
  2. A 2.5 3.5
  3. B 8.5 9.5

答案1

得分: 1

使用groupby.quantile,然后使用unstack

  1. df.groupby('code')['count'].quantile([0.25, 0.75]).unstack()

输出:

  1. 0.25 0.75
  2. code
  3. A 1.75 3.25
  4. B 7.75 9.25

使用以下格式:

  1. out = (df.groupby('code')['count']
  2. .quantile([0.25, 0.75]).unstack()
  3. .rename(columns=lambda x: f'{int(x*100)}QT')
  4. .reset_index()
  5. )

输出:

  1. code 25QT 75QT
  2. 0 A 1.75 3.25
  3. 1 B 7.75 9.25
英文:

Use groupby.quantile, then unstack:

  1. df.groupby('code')['count'].quantile([0.25, 0.75]).unstack()

Output:

  1. 0.25 0.75
  2. code
  3. A 1.75 3.25
  4. B 7.75 9.25

With the format:

  1. out = (df.groupby('code')['count']
  2. .quantile([0.25, 0.75]).unstack()
  3. .rename(columns=lambda x: f'{int(x*100)}QT')
  4. .reset_index()
  5. )

Output:

  1. code 25QT 75QT
  2. 0 A 1.75 3.25
  3. 1 B 7.75 9.25

huangapple
  • 本文由 发表于 2023年3月7日 21:40:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定