熊猫按功能过滤数据框行

Kar*_*ler 7 filter python-3.x pandas

我想根据行中的不同值通过更复杂的功能过滤数据帧。

是否有可能像您在ES6过滤器函数中那样通过布尔函数过滤DF行?

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

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)
Run Code Online (Sandbox Code Playgroud)

我发现使用apply()位的东西实际上使用布尔函数仅返回False/ True填充的行,这是预期的。

我的解决方法是在函数结果为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
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

我认为这里的功能不是必需的,更好,主​​要是更快地使用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]
Run Code Online (Sandbox Code Playgroud)

函数解决方案-仅需要返回布尔值,如果进行一些复杂的过滤则更好-仅需要为每行布尔返回值:

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]
Run Code Online (Sandbox Code Playgroud)


cot*_*ail 5

过滤数据帧的一种非常可读的方法是query

df.query("not (Name == 'Alisa' and Age > 24)")

# or pass the negation from the beginning (by de Morgan's laws)
df.query("Name != 'Alisa' or Age <= 24")
Run Code Online (Sandbox Code Playgroud)

另一种方法是将复杂的函数传递给loc过滤器。

df.loc[lambda x: ~((x['Name'] == 'Alisa') & (x['Age'] > 24))]
Run Code Online (Sandbox Code Playgroud)

资源