Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two or more columns in a dataframe into a new column with a new name

For example if I have this:

n = c(2, 3, 5)  s = c("aa", "bb", "cc")  b = c(TRUE, FALSE, TRUE)  df = data.frame(n, s, b)    n  s     b 1 2 aa  TRUE 2 3 bb FALSE 3 5 cc  TRUE 

Then how do I combine the two columns n and s into a new column named x such that it looks like this:

  n  s     b     x 1 2 aa  TRUE  2 aa 2 3 bb FALSE  3 bb 3 5 cc  TRUE  5 cc 
like image 608
user2654764 Avatar asked Aug 07 '13 23:08

user2654764


People also ask

How do I merge data frames with different column names?

Different column names are specified for merges in Pandas using the “left_on” and “right_on” parameters, instead of using only the “on” parameter. Merging dataframes with different names for the joining variable is achieved using the left_on and right_on arguments to the pandas merge function.

How do I combine two DataFrame columns?

By use + operator simply you can concatenate two or multiple text/string columns in pandas DataFrame.

How do I append two DataFrames in pandas with different column names?

It is possible to join the different columns is using concat() method. DataFrame: It is dataframe name. axis: 0 refers to the row axis and1 refers the column axis. join: Type of join.

Which function is used to join 2 or more columns together to form a data frame?

We can join columns from two Dataframes using the merge() function. This is similar to the SQL 'join' functionality. A detailed discussion of different join types is given in the SQL lesson.


1 Answers

Use paste.

 df$x <- paste(df$n,df$s)  df #   n  s     b    x # 1 2 aa  TRUE 2 aa # 2 3 bb FALSE 3 bb # 3 5 cc  TRUE 5 cc 
like image 83
mnel Avatar answered Sep 24 '22 00:09

mnel