Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column with values depending on another column to a dataframe [duplicate]

Tags:

dataframe

r

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.

like image 783
Ramona Avatar asked Jun 22 '18 12:06

Ramona


People also ask

How do you add a new column to a DataFrame based on another column?

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.

How do I get the value of a column based on another column value?

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.


2 Answers

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')
like image 75
Puddlebunk Avatar answered Oct 21 '22 12:10

Puddlebunk


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
like image 41
Lennyy Avatar answered Oct 21 '22 13:10

Lennyy