Home > Mobile >  How to convert a column in dataframe to only 0 or 1 in Data Science using python
How to convert a column in dataframe to only 0 or 1 in Data Science using python

Time:02-25

Suppose I have a dataset with several rows and columns, and I want a column to be displayed only in the form of 0s and 1s. That particular column does not contain categorical values, but just float values. So the task is wherever the values start with 0 or 0.34, 0.1, etc. must be represented as 0 and all other starting with 1 or 1.x, etc. will be represented as 1. Can anyone of you please help me with this?

CodePudding user response:

The dumb/straight forward way would be to change the values of the columns from float to int.

int(0.99)
... 0

int(1.53)
... 1

Of course, this will also make 2.10 into 2.

If you can define your criteria, use a lambda function.

df[col] = df[col].apply(lambda x : 0 if x<1 else 1)

CodePudding user response:

You can use the math's floor function

import math
df[col] = df[col].apply(math.floor)

-> math is a python build in library

  • Related