I have a data frame:
Code 401k CVS
101A true
231N true
FD54 true
99JB
85F4 true
I'm trying to replace the "true" character values with the respective column name (e.g. "401k"). This is my desired output:
Code 401k CVS
101A CVS
231N 401k
FD54 401k
99JB
85F4 401k
We can use ALTER TABLE ALTER COLUMN statement to change the datatype of the column.
DataFrame. replace() function is used to replace values in column (one value with another value on all columns). This method takes to_replace, value, inplace, limit, regex and method as parameters and returns a new DataFrame. When inplace=True is used, it replaces on existing DataFrame object and returns None value.
The coding below enabled me to replace every "true" value (character) into its respective column name.
##Replace every "true" value with its respective column name
w <- which(df=="true",arr.ind=TRUE)
df[w] <- names(df)[w[,"col"]]
This first method will do it without coercing the data to character first:
wc <- droplevels(col(df, as.factor=TRUE)[which(df == "true")])
df[levels(wc)] <- Map(factor, df[levels(wc)], labels = levels(wc))
df
# Code 401k CVS
# 1 101A <NA> CVS
# 2 231N 401k <NA>
# 3 FD54 401k <NA>
# 4 99JB <NA> <NA>
# 5 85F4 401k <NA>
Or you can use which
with the data frame indices and convert everything to character:
df[] <- lapply(df, function(x) levels(x)[x])
w <- which(df == "true", arr.ind = TRUE)
df[w] <- names(df)[w[,"col"]]
df
# Code 401K CVS
# 1 101A <NA> CVS
# 2 231N 401K <NA>
# 3 FD54 401K <NA>
# 4 99JB <NA> <NA>
# 5 85F4 401K <NA>
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