如何获取熊猫列的特定百分比跨度?

时间:2019-06-08 20:18:06

标签: python pandas numpy

假设我有一个数据框,其中包含有关城市公民的信息,包括其收入。我想将收入分解为百分位数,最高的1%,接下来的4%,接下来的15%,接下来的20%和最后的50%,并针对每个百分比来计算该百分比中的有多少公民,均值,收入总和等。 ..

我知道如何使用numpy.percentile方法找到百分位数,但是例如,我无法弄清楚如何找到前1%到其余95%之间的4%

2 个答案:

答案 0 :(得分:0)

如何获取百分位数并过滤数据框?例如尝试:

import pandas as pd
import numpy as np

# create dummy list of values and dataframe
vals = list(np.arange(100_001))
df = pd.DataFrame(vals, columns=["income"])

# filter on percentiles
df_4percent = df[(df.values_ > np.percentile(df.income, 1)) & (df.values_ < np.percentile(df.income, 5))]

答案 1 :(得分:0)

您想要pd.qcut

import { Directive, Input, TemplateRef, ViewContainerRef, ElementRef, AfterViewChecked } from '@angular/core';

@Directive({
  selector: '[replaceTag]'
})
export class ReplaceTagDirective implements AfterViewChecked {
  constructor(
    private templateRef: TemplateRef<any>,
    private vcf: ViewContainerRef
  ) { }
  private _tag: string;
  private _needUpdate: boolean = false;

  @Input('replaceTag')
  set tag(t: string): void {
    this._tag = t;
    this._needUpdate = true;
    this.vcf.clear();
    let template = this.templateRef.elementRef.nativeElement.nextElementSibling;
    if (template) {
      this.templateRef.elementRef.nativeElement.parentNode.removeChild(template);
    }
    this.vcf.createEmbeddedView(this.templateRef);
  }

  ngAfterViewChecked() {
    if (this._needUpdate) {
      this._updateTemplate();
      this._needUpdate = false;
    }
  }

  private _updateTemplate() {
    let template = this.templateRef.elementRef.nativeElement.nextElementSibling;
    if (template) {
      let r = document.createElement(this._tag);
      r.innerHTML = template.innerHTML;
      this.templateRef.elementRef.nativeElement.parentNode.replaceChild(r, template);
    }
  }
}

将为您提供相应的存储分区,您可以将其传递给pd.qcut(df['income'], [0,.5,.6,.8, .95, .99,1])

相关问题