sql - 在公共(public)列上连接两个数据框

标签 sql pandas join dataframe

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

orders 是一个 SQL Server 表:

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

客户是一个 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 文件的数据框执行此代码时,它工作正常。有什么帮助吗?

谢谢。

最佳答案

我认为问题是列 customerid 在两个 DataFrames 中具有不同的 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')

关于sql - 在公共(public)列上连接两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42947303/

相关文章:

sql - 将某个时间段内的所有日期插入表中

python - 填写 na 作为数据框的过滤器

python - pyspark 数据帧的缓慢过滤

sql - 使用 between operator 的 Hive 不等式连接

mysql选择问题,多表

sql - 唯一约束的可用性

c# - 使用 Dapper 将列表插入临时表

sql - 搜索和替换 SQL

python - 使用 numpy.max/numpy.min 作为时间戳值

MySql 显示不在第二个表中的值