Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append column to pandas dataframe

Tags:

python

pandas

This is probably easy, but I have the following data:

In data frame 1:

index dat1 0     9 1     5 

In data frame 2:

index dat2 0     7 1     6 

I want a data frame with the following form:

index dat1  dat2 0     9     7 1     5     6 

I've tried using the append method, but I get a cross join (i.e. cartesian product).

What's the right way to do this?

like image 279
BenDundee Avatar asked Dec 16 '13 03:12

BenDundee


People also ask

How do I append to a column in pandas?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.

How do I append to a specific column in a DataFrame?

Here are two commands which can be used: Use Dataframe join command to append the columns. Use Pandas concat command to append the columns. Both methods can be used to join multiple columns from different data frames and create one data frame.

How do you append to a specific column in Python?

Use concat() to Append a Column in Pandas We can use the concat function in Pandas to merge or concatenate multiple data frames into one with the help of a single argument that is passed as an array with all the data frames to be combined.


2 Answers

It seems in general you're just looking for a join:

> dat1 = pd.DataFrame({'dat1': [9,5]}) > dat2 = pd.DataFrame({'dat2': [7,6]}) > dat1.join(dat2)    dat1  dat2 0     9     7 1     5     6 
like image 106
U2EF1 Avatar answered Oct 09 '22 06:10

U2EF1


You can also use:

dat1 = pd.concat([dat1, dat2], axis=1) 
like image 43
Ella Cohen Avatar answered Oct 09 '22 06:10

Ella Cohen