Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

sql - join two dataframes on common column

I want to join two data sources, orders and customers:

orders is an SQL Server table:

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

and customers is a csv file:

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

I want to join these two tables in my Python application, so I wrote the following code:

# 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']])

I expect

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

But I get empty result.

When I perform this code for two data frames that are both from CSV files, it works fine. Any help?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think problem is columns customerid has different dtypes in both DataFrames so no match.

So need convert both columns to int or both to str.

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

Or:

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

Also is possible omit how='inner', because default value of merge:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...