Python,Pandas:根据函数过滤数据框的行

Lau*_*ura 3 python filter pandas

我正在尝试根据其中一列中的子字符串来过滤 python 数据框。

如果ID字段的位置13和14处的数字<=9,我想保留该行,如果它> 9,我想删除该行。

例子:

ABCD-3Z-A93Z-01A-11R-A37O-07 -> 保留

ABCD-3Z-A93Z-11A-11R-A37O-07 -> 掉落

我已经设法找到以下解决方案,但我认为必须有一种更快、更有效的方法。

import pandas as pd

# Enter some data. We want to filter out all rows where the number at pos 13,14 > 9
df = {'ID': ['ABCD-3Z-A93Z-01A-11R-A37O-07', 'ABCD-6D-AA2E-11A-11R-A37O-07', 'ABCD-6D-AA2E-01A-11R-A37O-07',
             'ABCD-A3-3307-01A-01R-0864-07', 'ABCD-6D-AA2E-01A-11R-A37O-07', 'ABCD-6D-AA2E-10A-11R-A37O-07',
             'ABCD-6D-AA2E-09A-11R-A37O-07'],
      'year': [2012, 2012, 2013, 2014, 2014, 2017, 2015]
}
# convert to df
df = pd.DataFrame(df)

# define a function that checks if position 13&15 are > 9.
def filter(x):
    # that, if x is a string,
    if type(x) is str:
        if int(float(x[13:15])) <= 9:
            return True
        else:
            return False
    else:
        return False

# apply function
df['KeepRow'] = df['ID'].apply(filter)
print(df)

# Now filter out rows where "KeepRow" = False
df = df.loc[df['KeepRow'] == True]
print(df)
# drop the column "KeepRow" as we don't need it anymore
df = df.drop('KeepRow', axis=1)
print(df)
Run Code Online (Sandbox Code Playgroud)

Ale*_*rov 5

我认为您可以根据字符串的第 13 个符号进行过滤:

将 pandas 导入为 pd

# Enter some data. We want to filter out all rows where the number at pos 13,14 > 9
df = pd.DataFrame({
    'ID': ['ABCD-3Z-A93Z-01A-11R-A37O-07',
           'ABCD-6D-AA2E-11A-11R-A37O-07',
           'ABCD-6D-AA2E-01A-11R-A37O-07',
           'ABCD-A3-3307-01A-01R-0864-07',
           'ABCD-6D-AA2E-01A-11R-A37O-07',
           'ABCD-6D-AA2E-10A-11R-A37O-07',
           'ABCD-6D-AA2E-09A-11R-A37O-07'],
    'year': [2012, 2012, 2013, 2014, 2014, 2017, 2015]
})
# convert to df

df['KeepRow'] = df['ID'].apply(lambda x: x[13] == '0')
Run Code Online (Sandbox Code Playgroud)

或者简单地:

df[df['ID'].apply(lambda x: x[13] == '0')]
Run Code Online (Sandbox Code Playgroud)