【问题标题】:Pandas: Inner Join returns no rowsPandas:内部联接不返回任何行
【发布时间】:2017-05-16 12:29:25
【问题描述】:

数据帧 1 (commits)

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

数据帧 2 (files)

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

我尝试将这些 DataFrame 与 df.merge 进行内部连接:

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

但它不返回任何行,尽管列名相同。

【问题讨论】:

  • 你试过了吗? - left_index=True, right_index=True ... 假设 CommitID 是两个 dfs 中的索引。

标签: python pandas dataframe


【解决方案1】:

CommitID 列的dtypes 存在不同的问题。

需要通过以下方式检查:

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

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    相关资源
    最近更新 更多