0

I am trying to replace all values in a specific column in a Dataframe if greater than 0. I tried the below but it replace all columns of that specific row.

df.loc[(df['count'] > 0)] = 1

Could anyone assist, thanks..

3 Answers 3

2

You are close, need specify column in second parameter:

df.loc[df['count'] > 0, 'count'] = 1

You can also specify multiple columns:

df.loc[df['count'] > 0, ['count', 'another col']] = 1

Another solution is:

df['count'] = np.where(df['count'] > 0, 1, df['count'])
#alternative    
#df['count'] = df['count'].mask(df['count'] > 0, 1)
Sign up to request clarification or add additional context in comments.

Comments

1

try the following sample of code; it is more felxible:

import pandas as pd
import numpy as np

data = np.random.randint(low=-2, high=3, size=10)
df = pd.DataFrame(data=data, columns=['value'])
df['new_value'] = df.value.apply(lambda i : i if i < 0 else 1)
print(df)

Result: enter image description here

Comments

0
df.loc[(df['count'] > 0), 'count'] = 1

I recommand this tutorial about .loc https://www.youtube.com/watch?v=xvpNA7bC8cs

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.