Home > Net >  Python Generate dummy in dataframe based on another variable(pandas)
Python Generate dummy in dataframe based on another variable(pandas)

Time:11-06

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.

CodePudding user response:

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)
  • Related