1

How can I replace the values of a DataFrame if are smaller or greater than a particular value?

print(df)

name            seq1   seq11
0     seq102    -14     -5.99   
1     seq103    -5.25   -7.94    

I want to set the values < than -8.5 to 1 and > than -8.5 to 0.

I tried this but all the values gets zero;

import pandas as pd
df = pd.read_csv('df.csv')
num = df._get_numeric_data() 
num[num < -8.50] = 1
num[num > -8.50] = 0

The desired output should be:

name            seq1   seq11
0     seq102      1       0   
1     seq103      0       0

Thank you

2 Answers 2

1

Try

num.iloc[:,1:] = num.iloc[:,1:].applymap(lambda x: 1 if x < -8.50 else 0)

Note that values equal to -8.50 will be set to zero here.

Sign up to request clarification or add additional context in comments.

Comments

0
def thresh(x):
    if(x < -8.5):
        return 1
    elif(x > -8.5):
        return 0
    return x

print(df[["seq1", "seq2"]].apply(thresh))

3 Comments

It's probably more efficient (and less verbose) to do this with a lambda function, especially since you're using apply.
I just assumed that it was strictly less than or strictly greater than, so there would be an elif. I don't think lambda functions can do elif right?
You can do it by inserting another if/else after the else operator, or just by stacking two applymaps.

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.