简体   繁体   中英

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

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

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 !

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM