5

suppose I've a pandas dataframe with column values as age like this df.age = {25, 35, 76, 21, 23, 30}

I want to do an inplace replace like this:

if df.age >=25 and df.age <= 35: replace that value with 1 else: replace that value with 0

I've tried this df[df.age >= 7.35 and df.age <= 7.45, 'age'] = 0 but doesn't seem to work.

1
  • 3
    Based on an answer that was just deleted, bear in mind that the correct syntax for the condition you're looking for is (df.age >= 25) & (df.age <= 35). Commented Oct 22, 2015 at 14:47

2 Answers 2

7

You can also create a function to check your conditions, and apply to the dataframe:

def condition(value):
    if 25 <= value <= 35:
        return 1
    return 0

# stealing sample from @AnandSKumar because I'm lazy
In [32]: df
Out[32]: 
   age
0   25
1   35
2   76
3   21
4   23
5   30

In [33]: df['age'] = df['age'].apply(condition)

In [34]: df
Out[34]: 
   age
0    1
1    1
2    0
3    0
4    0
5    1

Or using one liner with lambda:

df['age'] = df['age'].apply(lambda x: 1 if 25 <=  x <= 35 else 0)
Sign up to request clarification or add additional context in comments.

1 Comment

I really liked the lambda part alot, it gives me a lot of flexibility to extend the conditions if needed. Thanks!
4

You can compare the series with the values (25/35) according to your condition, and then use astype(int) to convert the True/False values, to 1/0. Example -

df['age'] = ((25 <= df['age']) & (df['age'] <= 35)).astype(int)

Demo -

In [2]: df = pd.DataFrame([[25], [35], [76], [21], [23], [30]],columns=['age'])

In [3]: df
Out[3]:
   age
0   25
1   35
2   76
3   21
4   23
5   30

In [6]: ((25 <= df['age']) & (df['age'] <= 35)).astype(int)
Out[6]:
0    1
1    1
2    0
3    0
4    0
5    1
Name: age, dtype: int32

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.