pandas: complex filter on rows of DataFrame

后端 未结 6 1571
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 15:22

I would like to filter rows by a function of each row, e.g.

def f(row):
  return sin(row[\'velocity\'])/np.prod([\'masses\']) > 5

df = pandas.DataFrame(.         


        
6条回答
  •  借酒劲吻你
    2020-12-04 15:29

    The best approach I've found is, instead of using reduce=True to avoid errors for empty df (since this arg is deprecated anyway), just check that df size > 0 before applying the filter:

    def my_filter(row):
        if row.columnA == something:
            return True
    
        return False
    
    if len(df.index) > 0:
        df[df.apply(my_filter, axis=1)]
    

提交回复
热议问题