[英]I need to calculate 1st and 3rd quartile in csv file without using numpy and pandas
[英]How to filter rows that fall within 1st and 3rd quartile of a particular column in pandas dataframe?
我正在使用python中的数据框如何过滤所有具有特定列值的行,例如val,它们属于第1和第3四分位数。
谢谢。
low, high = df.B.quantile([0.25,0.75])
df.query('{low}<B<{high}'.format(low=low,high=high))
让我们创建一些包含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
使用pd.Series.between()
并解df.A.quantile([lower, upper])
由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()
减慢了2x的速度:
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()
的解决方案完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.