Home > Software design >  Pandas: How to select rows where all column values are within a certain range?
Pandas: How to select rows where all column values are within a certain range?

Time:05-17

When I run below I get NameError: name 'apply' is not defined, How to select rows where all columns (a to f) value lies within -0.05 and 0.05 ?

import pandas as pd
import numpy as np

# example data generation
df = pd.DataFrame(np.random.randn(100, 6), columns=['a', 'b', 'c', 'd', 'e', 'f'])
df.head()

# How to select rows where all columns (a to f) value lies within -0.05 and 0.05 ?

df[apply(df >= -0.05 & df <= 0.05, 1, all), ]

CodePudding user response:

This should do what you're looking for:

results = df[((df >= -0.05) & (df <= 0.05)).all(axis=1)]

This will almost certainly result in an empty DataFrame for the randomly generated dataset given by the example code, but if you change the 0.05 values to give a much larger range, you'll see that it gives the expected results.

  • Related