Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge 2 columns into one in dataframe [closed]

Tags:

This should be simple, but I am struggling with it.

I want to combine two columns in a single dataframe into one. I have separate columns for custemer ID (20227) and year (2009). I want to create a new column that has both (2009_20227).

like image 869
Paul Avatar asked Jan 12 '15 16:01

Paul


People also ask

How do I merge two columns in a data frame?

By use + operator simply you can combine/merge two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.

How do I combine multiple columns into one in pandas?

You can use DataFrame. apply() for concatenate multiple column values into a single column, with slightly less typing and more scalable when you want to join multiple columns .

How do I convert multiple columns to single column in pandas?

Step #1: Load numpy and Pandas. Step #2: Create random data and use them to create a pandas dataframe. Step #3: Convert multiple lists into a single data frame, by creating a dictionary for each list with a name. Step #4: Then use Pandas dataframe into dict.

How do I merge two columns from a different DataFrame in pandas?

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.


1 Answers

You could use paste

transform(dat, newcol=paste(year, customerID, sep="_"))

Or use interaction

dat$newcol <- as.character(interaction(dat,sep="_"))

data

dat <- data.frame(year=2009:2013, customerID=20227:20231)
like image 195
akrun Avatar answered Sep 20 '22 04:09

akrun