I have got a dataframe to which I want to append a column with values depending on a column in my dataframe. My dataframe looks somewhat like this:
c1 c2 c3
x 2 z
y 5 f
c 3 r
a 11 z
Now I want to append another column c4
based on the values of c2
.
For all values between 0 and 4 I want to append "low"
, for values between 5 and 9 I want to append "medium"
and for those bigger than 10 "high"
.
c1 c2 c3 c4
x 2 z "low"
y 5 f "medium"
c 3 r "low"
a 11 z "high"
Probably the answer is quite simple, but I really can't think of something.
Using apply() method If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas. DataFrame. apply() method should do the trick.
You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression. The blow example returns a Courses column where the Fee column value matches with 25000.
You can nest ifelse
stataments. It's very handy when you are making categorical variables out of continuous ones.
data$c4 <- ifelse(data$c2 >= 0 & data$c2 <= 4, 'low',
ifelse(data$c2 >=5 & data$c2 <=9, 'medium',
ifelse(data$c2 >=10, 'High', 'something else')
df <- read.table(text = "
c1 c2 c3
x 2 z
y 5 f
c 3 r
a 11 z
", h = T)
df$c4 <- cut(df$c2, c(-Inf,4,9,Inf), c("low", "medium", "high"))
> df
c1 c2 c3 c4
1 x 2 z low
2 y 5 f medium
3 c 3 r low
4 a 11 z high
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