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
Using agg() to join pandas column If you need to join multiple string columns , you can use agg().
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.
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.
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)
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
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