Most operations in pandas
can be accomplished with operator chaining (groupby
, aggregate
, apply
, etc), but the only way I’ve found to filter rows is via normal bracket indexing
JavaScript
x
2
1
df_filtered = df[df['column'] == value]
2
This is unappealing as it requires I assign df
to a variable before being able to filter on its values. Is there something more like the following?
JavaScript
1
2
1
df_filtered = df.mask(lambda x: x['column'] == value)
2
Advertisement
Answer
I’m not entirely sure what you want, and your last line of code does not help either, but anyway:
“Chained” filtering is done by “chaining” the criteria in the boolean index.
JavaScript
1
13
13
1
In [96]: df
2
Out[96]:
3
A B C D
4
a 1 4 9 1
5
b 4 5 0 2
6
c 5 5 1 0
7
d 1 3 9 6
8
9
In [99]: df[(df.A == 1) & (df.D == 6)]
10
Out[99]:
11
A B C D
12
d 1 3 9 6
13
If you want to chain methods, you can add your own mask method and use that one.
JavaScript
1
29
29
1
In [90]: def mask(df, key, value):
2
return df[df[key] == value] .:
3
.:
4
5
In [92]: pandas.DataFrame.mask = mask
6
7
In [93]: df = pandas.DataFrame(np.random.randint(0, 10, (4,4)), index=list('abcd'), columns=list('ABCD'))
8
9
In [95]: df.ix['d','A'] = df.ix['a', 'A']
10
11
In [96]: df
12
Out[96]:
13
A B C D
14
a 1 4 9 1
15
b 4 5 0 2
16
c 5 5 1 0
17
d 1 3 9 6
18
19
In [97]: df.mask('A', 1)
20
Out[97]:
21
A B C D
22
a 1 4 9 1
23
d 1 3 9 6
24
25
In [98]: df.mask('A', 1).mask('D', 6)
26
Out[98]:
27
A B C D
28
d 1 3 9 6
29