Python 如何将一列从一个数据帧添加到另一个数据帧?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33497896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:27:36  来源:igfitidea点击:

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

pythonpandasipythondataframe

提问by user3307598

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

我有两个数据帧,一个 18x30(称为 df1)和一个 2x30(称为 df2),它们的索引值完全相同。

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

我希望能够将 df2 中的一列添加到 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.

df1 中的数据类型都是整数,df2 中的数据类型是字符串。每当我合并/连接/加入时,我都会得到 NaN 而不是正确的数据。

Any help would be greatly appreciated

任何帮助将不胜感激

Thanks :D

感谢:D

采纳答案by cggarvey

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.

df1 中的数据类型都是整数,df2 中的数据类型是字符串。每当我合并/连接/加入时,我都会得到 NaN 而不是正确的数据。

If you want to add the df2 value to the df1 value, you need to convert the df2 field to an integer.

如果要将 df2 值与 df1 值相加,则需要将 df2 字段转换为整数。

df2['FieldName'] = df2['FieldName'].astype(int)

回答by Harry_pb

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 !

这对我有用!