我有一个形状的数据框[600 000,19]。我想根据一个条件过滤前100 000行,根据另一个条件过滤下30万行,最后一行过滤第三个条件。我想知道如何做到这一点。
目前,我将数据框分成3个段并应用它们各自的条件。然后,我重新连接数据框。有没有更好的办法?
示例:根据任何小于5的值过滤前100 000行。对于第二个300 000行,我不希望任何大于40的值等。
您可以尝试以下方法:
import pandas as pd
sample = pd.DataFrame({'x' : pd.np.arange(100),
'colname': pd.np.arange(100)})
conditions = [('index < 5', 'colname < 3'),
('index > 50', 'index < 100', 'colname < 55')]
sample.query('|'.join(map(lambda x: '&'.join(x), conditions)))
方法是使用pd.concat
的数据框索引切片来构建完整的布尔系列:
import numpy as np
import pandas as pd
np.random.seed(0)
df=pd.DataFrame(np.random.randint(0,50,60))
df[pd.concat([df.iloc[:10] > 10, df[11:40] < 30, df[41:] % 2 == 0])]
前10个记录过滤少于10个,接下来30个值过滤大于30,最后一个值检查偶数。
然后,您可以使用dropna删除所有NaN值
输出:
0
0 44.0
1 47.0
2 NaN
3 NaN
4 NaN
5 39.0
6 NaN
7 19.0
8 21.0
9 36.0
10 NaN
11 6.0
12 24.0
13 24.0
14 12.0
15 1.0
16 NaN
17 NaN
18 23.0
19 NaN
20 24.0
21 17.0
22 NaN
23 25.0
24 13.0
25 8.0
26 9.0
27 20.0
28 16.0
29 5.0
30 15.0
31 NaN
32 0.0
33 18.0
34 NaN
35 24.0
36 NaN
37 29.0
38 19.0
39 19.0
40 NaN
41 NaN
42 32.0
43 NaN
44 NaN
45 32.0
46 NaN
47 10.0
48 NaN
49 NaN
50 NaN
51 28.0
52 34.0
53 0.0
54 0.0
55 36.0
56 NaN
57 38.0
58 40.0
59 NaN