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
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)
9 Comments
Marzieh Karimi
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
jezrael
@MarziehKarimi - Added to answer, if need new column use instead
df[1] = or df.iloc[:, 0] = this - df['dummy1'] = Marzieh Karimi
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')
jezrael
@MarziehKarimi - Can you show your complete code in question? also 5 rows of code before is raised errro.
|