python-3.x - Pandas 按功能过滤数据帧行

标签 python-3.x pandas filter

我想根据行中的不同值通过更复杂的函数过滤数据框。

是否有可能通过 bool 函数过滤 DF 行,就像你可以做到的那样,例如在 ES6 filter function ?

极端简化的例子来说明问题:

import pandas as pd

def filter_fn(row):
    if row['Name'] == 'Alisa' and row['Age'] > 24:
        return False

    return row

d = {
    'Name': ['Alisa', 'Bobby', 'jodha', 'jack', 'raghu', 'Cathrine',
             'Alisa', 'Bobby', 'kumar', 'Alisa', 'Alex', 'Cathrine'],
    'Age': [26, 24, 23, 22, 23, 24, 26, 24, 22, 23, 24, 24],

    'Score': [85, 63, 55, 74, 31, 77, 85, 63, 42, 62, 89, 77]}

df = pd.DataFrame(d, columns=['Name', 'Age', 'Score'])

df = df.apply(filter_fn, axis=1, broadcast=True)

print(df)

我发现了一些使用 apply() 位的东西,这实际上只返回 False/True使用 bool 函数填充行,这是预期的。

我的解决方法是在函数结果为 True 时返回行本身,否则返回 False。但这之后需要额外的过滤。
        Name    Age  Score
0      False  False  False
1      Bobby     24     63
2      jodha     23     55
3       jack     22     74
4      raghu     23     31
5   Cathrine     24     77
6      False  False  False
7      Bobby     24     63
8      kumar     22     42
9      Alisa     23     62
10      Alex     24     89
11  Cathrine     24     77

最佳答案

我认为在这里使用函数是不必要的。使用 boolean indexing 更好,主要更快:

m = (df['Name'] == 'Alisa') & (df['Age'] > 24)
print(m)
0      True
1     False
2     False
3     False
4     False
5     False
6      True
7     False
8     False
9     False
10    False
11    False
dtype: bool

#invert mask by ~
df1 = df[~m]
对于更复杂的过滤,您可以使用必须返回 bool 值的函数:
def filter_fn(row):
    if row['Name'] == 'Alisa' and row['Age'] > 24:
        return False
    else:
        return True

df = pd.DataFrame(d, columns=['Name', 'Age', 'Score'])
m = df.apply(filter_fn, axis=1)
print(m)
0     False
1      True
2      True
3      True
4      True
5      True
6     False
7      True
8      True
9      True
10     True
11     True
dtype: bool

df1 = df[m]

关于python-3.x - Pandas 按功能过滤数据帧行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51589573/

相关文章:

python - 我如何找到勒让德符号?

python-3.x - 无法在 Visual Studio 代码上导入 Tkinter?

python - 为什么我不能从 LDAP3 导入 LDAPBindError?

python - 如何整合 MS Teams 的出席名单?

c++ - 在同一解决方案的其他项目中的正确位置突出显示选定的 C/C++ 文件

python - 高效的字节浮点乘法

python - 具有按相邻列值进行多索引的 DataFrame 切片

python - Pandas 系列改造

python - 根据列中的不同条目过滤 pandas 数据框(逗号分隔的字符串列表)

mysql - Mysql 交集中的单列多过滤器