pandas 无法在字符串类型上加入熊猫数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52902909/
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-09-14 06:05:58  来源:igfitidea点击:

Unable to join pandas dataframe on string type

pythonpandasdataframe

提问by InAFlash

I have two DataFrames objects whose columns are as below

我有两个 DataFrames 对象,它们的列如下

Dataframe 1:

数据框 1:

df.dtypes

Output:

输出:

ImageID       object
Source        object
LabelName     object
Confidence     int64
dtype: object

Dataframe 2:

数据框 2:

a.dtypes

Output:

输出:

LabelName       object
ReadableName    object
dtype: object

Here, i am trying to combine these two dataframes as below

在这里,我试图将这两个数据框组合如下

combined =  df.join(a,on='LabelName')

But, i am getting the following error

但是,我收到以下错误

ValueError: You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat

ValueError: 您正在尝试合并 object 和 int64 列。如果你想继续,你应该使用 pd.concat

But, i am merging them on LabelName, which has only strings (object datatype)

但是,我将它们合并到 LabelName 上,它只有字符串(对象数据类型)

Am i missing something here?

我在这里错过了什么吗?

回答by John Zwinck

About the onparameter, the documentation says:

关于on参数,文档说:

Column or index level name(s) in the caller to join on the index in other, otherwise joins index-on-index.

调用者中的列或索引级别名称以加入其他中的索引,否则加入 index-on-index。

Note that join()always uses other.index. You can try this:

请注意,join()始终使用other.index. 你可以试试这个:

df.join(a.set_index('LabelName'), on='LabelName')

Or use df.merge()instead.

或者df.merge()改用。

回答by Karn Kumar

There is problem some columns are integers along with string in DataFrame1 while all are strings in DataFrame2 which is causing the problem.

有问题一些列是整数以及 DataFrame1 中的字符串,而 DataFrame2 中的所有列都是导致问题的字符串。

Simplest solution is cast all columns to strings:

最简单的解决方案是将所有列转换为字符串:

pd.merge(df1.astype(str),df2.astype(str), how='outer')

As the Value Error suggesting itself use concat:

作为建议本身使用 concat 的值错误:

pd.concat([df1, df2])

回答by Christopher Kinyua

Try converting the Confidence column to an object first because there is a dtype mismatch.

首先尝试将 Confidence 列转换为对象,因为存在 dtype 不匹配。

 df['Confidence'].apply(str)