pandas中的大多数操作都可以通过操作符链接(groupby、聚合、应用等)来完成,但我发现过滤行的唯一方法是通过普通的括号索引

df_filtered = df[df['column'] == value]

这是没有吸引力的,因为它要求我分配df到一个变量,然后才能过滤它的值。还有像下面这样的吗?

df_filtered = df.mask(lambda x: x['column'] == value)

当前回答

这个解决方案在实现方面比较粗糙,但我发现它在使用方面更简洁,而且肯定比其他提出的解决方案更通用。

https://github.com/toobaz/generic_utils/blob/master/generic_utils/pandas/where.py

你不需要下载整个回购:保存文件和做

from where import where as W

应该足够了。然后你可以这样使用它:

df = pd.DataFrame([[1, 2, True],
                   [3, 4, False], 
                   [5, 7, True]],
                  index=range(3), columns=['a', 'b', 'c'])
# On specific column:
print(df.loc[W['a'] > 2])
print(df.loc[-W['a'] == W['b']])
print(df.loc[~W['c']])
# On entire - or subset of a - DataFrame:
print(df.loc[W.sum(axis=1) > 3])
print(df.loc[W[['a', 'b']].diff(axis=1)['b'] > 1])

一个稍微不那么愚蠢的用法示例:

data = pd.read_csv('ugly_db.csv').loc[~(W == '$null$').any(axis=1)]

顺便说一下,即使在使用布尔cols的情况下,

df.loc[W['cond1']].loc[W['cond2']]

能比吗

df.loc[W['cond1'] & W['cond2']]

因为它只在cond1为True时计算cond2。

免责声明:我第一次给出这个答案是因为我没有看到这个。

其他回答

来自@lodagro的答案很棒。我将通过泛化掩码函数来扩展它:

def mask(df, f):
  return df[f(df)]

然后你可以这样做:

df.mask(lambda x: x[0] < 0).mask(lambda x: x[1] > 0)

您还可以利用numpy库进行逻辑操作。它相当快。

df[np.logical_and(df['A'] == 1 ,df['B'] == 6)]

这个解决方案在实现方面比较粗糙,但我发现它在使用方面更简洁,而且肯定比其他提出的解决方案更通用。

https://github.com/toobaz/generic_utils/blob/master/generic_utils/pandas/where.py

你不需要下载整个回购:保存文件和做

from where import where as W

应该足够了。然后你可以这样使用它:

df = pd.DataFrame([[1, 2, True],
                   [3, 4, False], 
                   [5, 7, True]],
                  index=range(3), columns=['a', 'b', 'c'])
# On specific column:
print(df.loc[W['a'] > 2])
print(df.loc[-W['a'] == W['b']])
print(df.loc[~W['c']])
# On entire - or subset of a - DataFrame:
print(df.loc[W.sum(axis=1) > 3])
print(df.loc[W[['a', 'b']].diff(axis=1)['b'] > 1])

一个稍微不那么愚蠢的用法示例:

data = pd.read_csv('ugly_db.csv').loc[~(W == '$null$').any(axis=1)]

顺便说一下,即使在使用布尔cols的情况下,

df.loc[W['cond1']].loc[W['cond2']]

能比吗

df.loc[W['cond1'] & W['cond2']]

因为它只在cond1为True时计算cond2。

免责声明:我第一次给出这个答案是因为我没有看到这个。

我提供了更多的例子。这个答案和https://stackoverflow.com/a/28159296/是一样的

我将添加其他编辑,使这篇文章更有用。

pandas.DataFrame.query 查询正是为了这个目的。考虑数据框架df

import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(10, 5)),
    columns=list('ABCDE')
)

df

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
6  8  7  6  4  7
7  6  2  6  6  5
8  2  8  7  5  8
9  4  7  6  1  5

让我们使用查询过滤所有行D > B

df.query('D > B')

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
7  6  2  6  6  5

我们把它串起来

df.query('D > B').query('C > B')
# equivalent to
# df.query('D > B and C > B')
# but defeats the purpose of demonstrating chaining

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
4  3  6  7  7  4
5  5  3  7  5  9
7  6  2  6  6  5

如果将列设置为作为索引进行搜索,则可以使用DataFrame.xs()获取横截面。这没有查询答案那么通用,但在某些情况下可能很有用。

import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(3, size=(10, 5)),
    columns=list('ABCDE')
)

df
# Out[55]: 
#    A  B  C  D  E
# 0  0  2  2  2  2
# 1  1  1  2  0  2
# 2  0  2  0  0  2
# 3  0  2  2  0  1
# 4  0  1  1  2  0
# 5  0  0  0  1  2
# 6  1  0  1  1  1
# 7  0  0  2  0  2
# 8  2  2  2  2  2
# 9  1  2  0  2  1

df.set_index(['A', 'D']).xs([0, 2]).reset_index()
# Out[57]: 
#    A  D  B  C  E
# 0  0  2  2  2  2
# 1  0  2  1  1  0