【问题标题】:How to filter rows that fall within 1st and 3rd quartile of a particular column in pandas dataframe?如何过滤落在熊猫数据框中特定列的第一个和第三个四分位数内的行?
【发布时间】:2016-08-12 12:46:07
【问题描述】:

我正在处理 python 中的数据框我如何过滤所有具有特定列值的行,例如 val,它们位于第一个和第三个四分位数之内。

谢谢。

【问题讨论】:

  • 是的,我看到了,但仍然无法弄清楚。
  • 向我们展示您目前的代码,即使它没有完全工作。
  • 我有一个数据框,其中有一列名为“educationnum”。我想选择所有在 'educationnum' 的第一个和第三个四分位数内的行。

标签: python python-2.7 pandas dataframe


【解决方案1】:
low, high = df.B.quantile([0.25,0.75])
df.query('{low}<B<{high}'.format(low=low,high=high))

【讨论】:

  • 收到此错误:/: 'list' 和 'float' 的操作数类型不受支持
  • 你使用的是哪个版本的熊猫?
  • 熊猫版本是0.13.1
  • 版本有问题,现在解决了。谢谢
【解决方案2】:

让我们创建一些 100 行和 3 列的随机数据:

import numpy as np
import pandas as pd

np.random.seed(0)

df = pd.DataFrame(np.random.randn(100, 3), columns=list('ABC'))

现在让我们使用loc 过滤掉列B 上下四分位数上方和下方的所有数据(保留中间)。

lower_quantile, upper_quantile = df.B.quantile([.25, .75])

>>> df.loc[(df.B > lower_quantile) & (df.B < upper_quantile)].head()
           A         B         C
0   1.764052  0.400157  0.978738
2   0.950088 -0.151357 -0.103219
3   0.410599  0.144044  1.454274
4   0.761038  0.121675  0.443863
10  0.154947  0.378163 -0.887786

【讨论】:

  • 收到此错误:/: 'list' 和 'float' 的操作数类型不受支持
【解决方案3】:

使用pd.Series.between() 并解压缩df.A.quantile([lower, upper]) 生成的quantile 值,您可以过滤您的DataFrame,此处使用0-100 范围内的示例数据进行说明:

import numpy as np
import pandas as pd

df = pd.DataFrame(data={'A': np.random.randint(0, 100, 10), 'B': np.arange(10)})

    A  B
0   4  0
1  21  1
2  96  2
3  50  3
4  82  4
5  24  5
6  93  6
7  16  7
8  14  8
9  40  9

df[df.A.between(*df.A.quantile([0.25, 0.75]).tolist())]


    A  B
1  21  1
3  50  3
5  24  5
9  40  9

关于性能:.query() 将速度减慢 2 倍:

df = DataFrame(data={'A': np.random.randint(0, 100, 1000), 'B': np.arange(1000)})

def query(df):
    low, high = df.B.quantile([0.25,0.75])
    df.query('{low}<B<{high}'.format(low=low,high=high))

%timeit query(df)
1000 loops, best of 3: 1.81 ms per loop

def between(df):
    df[df.A.between(*df.A.quantile([0.25, 0.75]).tolist())]

%timeit between(df)
1000 loops, best of 3: 995 µs per loop

@Alexander 的解决方案与使用 .between() 的解决方案执行相同。

【讨论】:

  • fyi,between 可能会在 0.18.1 中弃用。
  • 谢谢,这很有帮助。
  • 我收到此错误:/: 'list' 和 'float' 的操作数类型不受支持
  • 能否显示堆栈跟踪以查看错误来源?理想情况下,还可以显示您的一些数据或df.info() 的输出。
  • TypeError Traceback (最近一次调用最后一次) in () ----> 1 df2=d[d.educationnum.between(*d. educationnum.quantile([0.25, 0.75]).tolist())] /usr/lib/python2.7/dist-packages/pandas/core/series.pyc in quantile(self, q) 1322 if len(valid_values) = = 0: 1323 return pa.NA -> 1324 result = _quantile(valid_values, q * 100) 1325 if result.dtype == _TD_DTYPE: 1326 from pandas.tseries.timedeltas import to_timedelta TypeError: unsupported operand type(s) for /: “列表”和“浮动”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2018-02-06
  • 2021-08-25
  • 1970-01-01
  • 2019-10-27
  • 2018-10-24
相关资源
最近更新 更多