EverGreen22
EverGreen22

Reputation: 47

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

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), ]

Upvotes: 1

Views: 2104

Answers (1)

sjw
sjw

Reputation: 6543

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.

Upvotes: 3

Related Questions