我有一個 python 代碼,用于從帶有兩個嵌套“for”回圈的較大表中的一個非常小的表中搜索資料。在我看來,它效率不高。
使用熊貓可能會快得多,但我進行合并的方式將重復值添加到輸出資料幀。如何僅將第一個匹配項添加到資料框中?也就是說,獲得與嵌套“for”回圈相同的結果
這是'main_table'資料框,我需要在'table_to_search'資料框的'hotel Name'中搜索'hotel name column'的每個值
main_table:
Discount hotel name
0 0.00 hotel A
1 0.10 hotel B
2 0.10 hotel C
3 0.15 hotel D
4 0.20 hotel E
5 0.30 hotel F
6 0.30 hotel G
7 1.00 hotel H
使用回圈我得到以下結果:
['Groups', 'Offline TA/TO', 'Online TA', 'Online TA', 'Offline TA/TO', 'Offline TA/TO', 'Online TA', 'Direct']
和熊貓我得到以下內容:
out:
Discount hotel name vlookup_column
0 0.00 hotel A Groups
1 0.00 hotel A Online TA
2 0.10 hotel B Offline TA/TO
3 0.10 hotel C Online TA
4 0.10 hotel C Online TA
5 0.10 hotel C Corporate
6 0.15 hotel D Online TA
7 0.20 hotel E Offline TA/TO
8 0.20 hotel E Direct
9 0.20 hotel E Online TA
10 0.30 hotel F Offline TA/TO
11 0.30 hotel F Online TA
12 0.30 hotel G Online TA
13 1.00 hotel H Direct
如您所見,輸出資料幀包含重復項。
我想要的資料框如下:
out:
Discount hotel name vlookup_column
0 0.00 hotel A Groups
1 0.10 hotel B Offline TA/TO
2 0.10 hotel C Online TA
3 0.15 hotel D Online TA
4 0.20 hotel E Offline TA/TO
5 0.30 hotel F Offline TA/TO
6 0.30 hotel G Online TA
7 1.00 hotel H Direct
這是我的python代碼:
import pandas as pd
from datetime import datetime
start_time = datetime.now()
file_path = r'/Users/myuser/Desktop/VLOOKUP_TEST/hotel_data.xlsx'
main_table = pd.read_excel(file_path, 'market_segment', header = 0)
print(main_table)
table_to_search = pd.read_excel(file_path, '2018', header = 0)
print ('\nVLOOKUP with loop')
loop_vlookup = []
for k in range(0, len(main_table['hotel name'])):
status = False
for item in range(0, len(table_to_search['hotel Name'])) :
if str(main_table['hotel name'][k]) == table_to_search['hotel Name'][item]:
print('coincidence')
loop_vlookup.append(table_to_search['market_segment'][item])
status = True
break
if not status:
loop_vlookup.append("")
print("\n",loop_vlookup)
# Pandas VLOOKUP
print("\nPandas VLOOKUP")
mapping = {'hotel Name': 'hotel name', 'market_segment' : 'vlookup_column'}
out = main_table.merge(table_to_search.rename(columns=mapping)[['hotel name','vlookup_column']], on = 'hotel name')
print(out)
我怎么能修改pandas merge只獲得第一場比賽?
在這里你可以找到excel檔案:https : //drive.google.com/drive/folders/1bbXQtRvWDq84rOf2xBwRkVvSOVULF2Jt? usp =sharing
uj5u.com熱心網友回復:
也許這就是你所需要的。另外,永遠不要在熊貓中使用 for 回圈。閱讀有關熊貓合并的更多資訊
#Merge based on "hotel name" key
main_table = pd.read_excel(file_path, 'market_segment', header = 0)
ref_table = pd.read_excel(file_path, '2018', header = 0)
df = pd.merge(main_table, ref_table, on="hotel name", how="left")
#keep only first results
df = df.drop_duplicates(subset=["Discount", "hotel name"], keep="first")
uj5u.com熱心網友回復:
隨著你的出去
new = out.drop_duplicates(['discount', 'hotel name'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/397666.html
