【问题标题】:Joining two dataframes on columns they match在它们匹配的列上连接两个数据框
【发布时间】:2020-10-24 23:31:59
【问题描述】:

我有两个数据框。 df1 在“Table_name”列中的元素 (3) 比 df2 (2) 多。我想要一个只输出 df1 和 df2 共享相同列名的行的结果数据框。

df1

Table_Name | Type
   id      | int
   name    | string
   position| string

df2

Table_Name | Type
   id      | float
   name    | string

我希望这是结果。

df_result

Table_Name | Type
   id      | int
   name    | string

这是我尝试过的,但它不起作用:

similar_cols = df1[df1['Table_name'].isin(df2['Table_name'])].dropna()

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你需要loc这里

    similar_cols = df1.loc[df1['Table_name'].isin(df2['Table_name'])]
    

    【讨论】:

    • 谢谢你的回答!我在运行时收到此错误IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match
    • 啊!它仍然给出相同的原始结果。我没有返回与 df2 具有相同大小和 col_names 的数据框,而是在 df1 中得到相同的值
    • @user3796292 我尝试了您的示例数据框,它在我的最终工作
    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    相关资源
    最近更新 更多