首页 > 解决方案 > 如何使用函数过滤数据框?

问题描述

我想使用以下函数来过滤数据帧

def isInRadius(position):
    latCheck = False
    lonCheck = False
    if position.lat < 0:
        latCheck = position.lat <= upperLat and position.lat >= lowerLat
    else:
        latCheck = position.lat >= upperLat and position.lat <= lowerLat

    if not latCheck:
        return False

    if position.lon < 0:
        lonCheck = position.lon <= righterLon and position.lon >= lefterLon
    else:
        lonCheck = position.lon >= righterLon and position.lat <= lefterLon

    return latCheck and lonCheck

数据框的列比 'lat' 和 'lon' 多,但我想根据上面函数实现的逻辑按这 2 列过滤它。

我尝试过dataFrame.filter(lambda x: isInRadius(x))和其他方法dataFrame.filter(isInRadius)dataFrame.filter(lambda x: isInRadius(x.iLoc[0]))但没有奏效,导致错误“TypeError:'function' object is not iterable”

我该怎么做?

在 C# 上我会做

var filtered = myCollection.Where(x => isInRadius(x));

标签: pythonpandasdataframe

解决方案


只需使用.apply熊猫数据框的功能

df[df.apply(isInRadius, 1)]

推荐阅读