Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...