Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join/merge two columns inside a data-frame

Say I have this data,

(df <- data.frame( col1 = c('My','Your','His','Thir'), col2 = c('Cat','Dog','Fish','Dog')))

  col1 col2
1   My  Cat
2 Your  Dog
3  His Fish
4 Thir  Dog

and I want to combine the columns like this

`some magic`

  col1 col2      col3
1   My  Cat    My Cat
2 Your  Dog  Your Dog
3  His Fish  His Fish
4 Thir  Dog  Thir Dog

What do I do? maybe even with a comma (,) like this,

`some magic`

  col1 col2      col3
1   My  Cat    My, Cat
2 Your  Dog  Your, Dog
3  His Fish  His, Fish
4 Thir  Dog  Thir, Dog
like image 312
Eric Fail Avatar asked Nov 28 '12 01:11

Eric Fail


People also ask

How do I merge all columns into one in pandas?

Using agg() to join pandas column If you need to join multiple string columns , you can use agg().

What are the different types of joins when merging two data frames?

one-to-one joins: for example when joining two DataFrame objects on their indexes (which must contain unique values). many-to-one joins: for example when joining an index (unique) to one or more columns in a different DataFrame . many-to-many joins: joining columns on columns.

How do I merge column values in pandas?

To start, you may use this template to concatenate your column values (for strings only): df['New Column Name'] = df['1st Column Name'] + df['2nd Column Name'] + ... Notice that the plus symbol ('+') is used to perform the concatenation.


2 Answers

If you want to leave them as a list of the two, (not a string concatenating both) then the following will work well

within(df, col3 <- Map(list, as.character(col1),as.character(col2)))  

  col1 col2      col3
1   My  Cat   My, Cat
2 Your  Dog Your, Dog
3  His Fish His, Fish
4 Thir  Dog Thir, Dog

Map is a simple wrapper for mapply(..., SIMPLIFY = FALSE)

like image 34
mnel Avatar answered Oct 12 '22 23:10

mnel


df$col3 <- paste(df$col1, df$col2, sep=","). You can also use the sprintf and paste0 functions.

df$col3 <- paste(df$col1, df$col2, sep=",") # comma separator
df$col3 <- paste0(df$col1, df$col2) # for no separator
like image 55
Erik Shilts Avatar answered Oct 13 '22 01:10

Erik Shilts