1

I have dataframe with many variables. I would like to generate a dummy variable based on column 1, for example. If column 1's observation is more than 0.25 then the dummy variable is filled with 1. If column 1' observation is less than 0.25, then the dummy variable is filled with 0. Any ideas? Thanks a lot.

1 Answer 1

1

IIUC compare values for greater like 0.25 and then cast to integers for map True/False to 1/0:

df[1] = df[1].gt(0.25).astype(int)

If first column:

df.iloc[:, 0] = df.iloc[:, 0].gt(0.25).astype(int)
Sign up to request clarification or add additional context in comments.

9 Comments

how can I add this dummy variable to my dataframe? I used 'df[dummy]=df[1].gt(0.25).astype(int)' but it didnt work
@MarziehKarimi - Added to answer, if need new column use instead df[1] = or df.iloc[:, 0] = this - df['dummy1'] =
I used the first code but I received this error : ('<ipython-input-86-7f424b93050c>:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead')
@MarziehKarimi - Can you show your complete code in question? also 5 rows of code before is raised errro.
@MarziehKarimi - I think by edit
|

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.