Pandas:Inner Join不返回任何行

时间:2017-05-16 12:29:25

标签: python pandas dataframe

DataFrame 1(commits

CommitID  | COMMITTER  
------------------------
  1       | A         
  2       | B         
  3       | B         

DataFrame 2(files

CommitID  | MOD
------------------------
  1       | 0         
  2       | 1         
  3       | 7       

我尝试使用df.merge

将这些DataFrame内部加入

files.merge(right=commits, how='inner',left_on="CommitID", right_on="CommitID")

但它并没有返回任何行,尽管列名相同。

1 个答案:

答案 0 :(得分:2)

dtypes的问题不同CommitID

需要通过以下方式检查:

print (files['CommitID'].dtypes)
print (commits['CommitID'].dtypes)

然后按astype转换为同一个:

#change only object
files['CommitID'] = files['CommitID'].astype(int)
commits['CommitID'] = commits['CommitID'].astype(int)
#change only int
files['CommitID'] = files['CommitID'].astype(str)
commits['CommitID'] = commits['CommitID'].astype(str)

您的代码可以简化 - 省略默认how='inner并仅使用on

df = files.merge(right=commits, on="CommitID")
print (df)
   CommitID  MOD COMMITTER
0         1    0         A
1         2    1         B
2         3    7         B

或者DataFrames中只有相同的连接列:

df = files.merge(right=commits)
print (df)
   CommitID  MOD COMMITTER
0         1    0         A
1         2    1         B
2         3    7         B