Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a column from one dataframe to another dataframe?

Tags:

I have two dataframes, one 18x30 (called df1) and one 2x30 (called df2), both of them have exactly the same index values.

I want to be able to add one of the columns from df2 to the end of df1.

The data types in df1 are all integer and the data type for df2 is string. Whenever I merge/concat/join, I get NaN instead of the right data.

Any help would be greatly appreciated

Thanks :D

like image 529
user3307598 Avatar asked Nov 03 '15 11:11

user3307598


People also ask

How do you add a column to a DataFrame based on another column?

Using apply() method If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas. DataFrame. apply() method should do the trick.

How do you add data from one DataFrame to another in python?

append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value.

How do I add multiple columns from one DataFrame to another in python?

Add multiple columns to a data frame using Dataframe. assign() method. Using DataFrame. assign() method, we can set column names as parameters and pass values as list to replace/create the columns.

How do I combine columns of different data frames?

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.


2 Answers

if you want to add the column at the end, you can use

df1['columename']= df2['existing_colume_name']

and after that apply

df1.column_name = df1.column_name.astype(float)

This worked for me !

like image 95
Hari_pb Avatar answered Sep 22 '22 15:09

Hari_pb


correct answer:

df1['column_name'] = df2['column_name'].values

the thing is you need to pass an object of a certain type for it to work correctly. List or array are preferable.

like image 31
zzHQzz Avatar answered Sep 22 '22 15:09

zzHQzz