How can I add a column from one dataframe to another dataframe?
Solution 1
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.
If you want to add the df2 value to the df1 value, you need to convert the df2 field to an integer.
df2['FieldName'] = df2['FieldName'].astype(int)
Solution 2
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 !
Solution 3
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.
Related videos on Youtube
user3307598
Updated on December 09, 2020Comments
-
user3307598 over 3 years
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
-
alex314159 over 8 yearswhat is happening if you just do df1['newcol']=df2['col'] ?
-
user3307598 over 8 yearsNevermind, solved it. Just needed to change the datatype
-