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
1.7k views
in Technique[技术] by (71.8m points)

pandas - How to merge two Excel files in Python?

I want to merge two excel files in Python.

File1:

Number  - Date
11      - 2020-10-10
2       - 2020-10-11
30      - 2020-10-11
14      - 2020-10-11

File2:

Number - Type
19     - 110
23     - 110
65     - 110
2      - 134
14     - 260
31     - 260
30     - 299
11     - 299

This is what I tried:

import pandas as pd

df1 = pd.read_excel('file1.xlsx') 
df2 = pd.read_excel('file2.xlsx')

df1['Type'] = df1['Number'].map(df2.set_index('Number')['Type'])

This is what I got:

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

This is what I expected:

Number  - Date         -  Type
11      - 2020-10-10   -  299
2       - 2020-10-11   -  134
30      - 2020-10-11   -  299
14      - 2020-10-11   -  260

I checked other questions in SO but I could not find a proper answers

question from:https://stackoverflow.com/questions/65830143/how-to-merge-two-excel-files-in-python

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

1 Reply

0 votes
by (71.8m points)

Dosen't this work?

df1.merge(df2, on='Number', how='left')

   Number        Date  Type
0      11  2020-10-10   299
1       2  2020-10-11   134
2      30  2020-10-11   299
3      14  2020-10-11   260

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

1.4m articles

1.4m replys

5 comments

57.0k users

...