【问题标题】:join two dataframes on common column在公共列上连接两个数据框
【发布时间】:2017-03-22 09:22:09
【问题描述】:

我想加入两个数据源,订单和客户:

orders 是一个 SQL Server 表:

orderid| customerid | orderdate | ordercost
------ | -----------| --------- | --------
12000  | 1500       |2008-08-09 |  38610

customers 是一个 csv 文件:

customerid,first_name,last_name,starting_date,ending_date,country
1500,Sian,Read,2008-01-07,2010-01-07,Greenland

我想在我的 Python 应用程序中加入这两个表,所以我编写了以下代码:

# Connect to SQL Sever with Pyodbc library

connection = pypyodbc.connect("connection string here")
cursor=connection.cursor();
cursor.execute("SELECT * from order)
result= cursor.fetchall()

# convert the result to pandas Dataframe
df1 = pd.DataFrame(result, columns= ['orderid','customerid','orderdate','ordercost'])

# Read CSV File
df2=pd.read_csv(customer_csv)

# Merge two dataframes
merged= pd.merge( df1, df2, on= 'customerid', how='inner')
print(merged[['first_name', 'country']])

我期待

first_name | country
-----------|--------
Sian       | Greenland

但我得到空结果。

当我对都来自 CSV 文件的两个数据帧执行此代码时,它工作正常。有什么帮助吗?

谢谢。

【问题讨论】:

    标签: sql pandas join dataframe


    【解决方案1】:

    我认为问题是列customeridDataFrames 中都有不同的dtypes,所以不匹配。

    因此需要将两列都转换为int 或两者都转换为str

    df1['customerid'] = df1['customerid'].astype(int)
    df2['customerid'] = df2['customerid'].astype(int)
    

    或者:

    df1['customerid'] = df1['customerid'].astype(str)
    df2['customerid'] = df2['customerid'].astype(str)
    

    也可以省略how='inner',因为merge的默认值:

    merged= pd.merge( df1, df2, on= 'customerid')
    

    【讨论】:

    • 是的,问题是 'customerid' 的类型是 object ,所以我将它转换为 int 并且它现在可以工作了,谢谢。
    • 感谢您的接受,您的问题已被赞成。美好的一天!
    【解决方案2】:

    pd.merge 的空数据帧结果意味着您在两个帧中没有任何匹配值。你检查过数据的类型吗?使用

    df1['customerid'].dtype
    

    检查。

    除了在导入后进行转换(如另一个答案中所建议的那样),您还可以在阅读 csv 时告诉 pandas 您想要什么 dtype

    df2=pd.read_csv(customer_csv, dtype={'customerid': str))
    

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 2021-11-27
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多