In the R cli I am able to do the following on a character column in a data frame:
> data.frame$column.name [data.frame$column.name == "true"] <- 1 > data.frame$column.name [data.frame$column.name == "false"] <- 0 > data.frame$column.name <- as.integer(data.frame$column.name)
I would like to do this as a function and I tried the following code, inputing data.frame$column.name as arg1. I see that it is working when I return(arg1) but how do I return the operation to the original data.frame?
boolean.integer <- function(arg1) { arg1 [arg1 == "true"] <- 1 arg1 [arg1 == "false"] <- 0 arg1 <- as.integer(arg1) }
In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values. int() turns the boolean into 1 or 0. Note: that any value not equal to 'true' will result in 0 being returned.
You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.
DataFrame - assign() function The assign() function is used to assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. The column names are keywords.
To convert boolean to integer in python, we will use int(bool) and then it will be converted to integer.
@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With