[*初部已解決*]python配對兩個sheet COL資料加速方法

本帖最後由 bongbong3481 於 2023-9-8 16:41 編輯

暫時算滿意的2個方案:  
(1) EXCEL COL 資料放晒入LIST,  然後用2個for in range ,  唔計LOADING, 2個for in range 用左1 分20秒
(2) 問左BING CHAT 將以下的CODE 改為 python list comprehension: list4 = [list3[list2.index(txt)] if txt in list2 else None for txt in list1], 唔計LOADING, list comprehension只用26秒  , 我覺得用CPYTHON 有可能仲快,  不過自己唔識, 而且好滿意


for i in range(10000):

        txt=list1
        for c in range(150000):
       
                if txt==list2[c]:
                       
                        list4=list3[c]
                        break

===================
有2個excel sheet A 及B,  想將sheet B 內資料,按照SHEET A內 COL 1 遂行配對番,在EXCEL用VLOOKUP就搞好。PYTHON 用PANDAS LEFT JOIN都好快做好。

但用傳統FOR LOOP方法, OPENPYXL用了2個FOR LOOP(CODE 系下面),結果慢到想嘔 (平時VBA 我將資料放入ARRAY 內都可以好快)。  

請問PYTHON點樣可以加速,除左用PANDAS,是否只能將資料放入array 內運算,運算完再搬入excel?

from openpyxl import load_workbook
workbook9 = load_workbook('A.xlsx')
worksheet9 = workbook9.active

workbook10 = load_workbook('B.xlsx')
worksheet10 = workbook10.active


w9_max=10000
w10_max=150000

for i in range(2,w9_max):

        temp9=worksheet9.cell(row=i, column=1).value

        for c in range(2,w10_max):           
               temp10=worksheet10.cell(row=c, column=1).value

               if (temp9 == temp10):

                       worksheet9.cell(row=i, column=7).value=worksheet10.cell(row=c, column=19).value

                       break

workbook9.save('output.xlsx')

There are several ways to improve the performance of matching data between two Excel sheets using Python without relying on the traditional nested for loop approach. Here are a few suggestions:

1. **Pandas**: As you mentioned, using the `pandas` library is a quick and efficient way to perform data manipulation and merging operations. You can load both sheets into pandas DataFrames, perform a left join on the desired columns, and then save the result back to an Excel file. Here's an example:

```python
import pandas as pd

df1 = pd.read_excel('A.xlsx')
df2 = pd.read_excel('B.xlsx')

merged_df = pd.merge(df1, df2, left_on='COL 1', right_on='COL 1', how='left')

merged_df.to_excel('output.xlsx', index=False)
```

2. **Dictionary-based approach**: You can use dictionaries to create a lookup table for faster matching. This approach avoids the need for nested loops. Here's an example:

```python
from openpyxl import load_workbook

workbook9 = load_workbook('A.xlsx')
worksheet9 = workbook9.active

workbook10 = load_workbook('B.xlsx')
worksheet10 = workbook10.active

w9_max = 10000
w10_max = 150000

lookup_dict = {}

# Populate the lookup dictionary
for c in range(2, w10_max):
    temp10 = worksheet10.cell(row=c, column=1).value
    lookup_dict[temp10] = worksheet10.cell(row=c, column=19).value

# Match and update values in Sheet A
for i in range(2, w9_max):
    temp9 = worksheet9.cell(row=i, column=1).value

    if temp9 in lookup_dict:
        worksheet9.cell(row=i, column=7).value = lookup_dict[temp9]

workbook9.save('output.xlsx')
```

By using a dictionary to store the values from Sheet B, you can perform lookups in constant time, significantly improving the performance compared to nested loops.

3. **Numpy**: If you prefer working with arrays, you can utilize the `numpy` library to convert the Excel data into arrays and perform the matching operation. However, keep in mind that this approach may consume more memory compared to the previous methods. Here's an example:

```python
import numpy as np
from openpyxl import load_workbook

workbook9 = load_workbook('A.xlsx')
worksheet9 = workbook9.active

workbook10 = load_workbook('B.xlsx')
worksheet10 = workbook10.active

w9_max = 10000
w10_max = 150000

# Convert Sheet A to a numpy array
data9 = np.array([[worksheet9.cell(row=i, column=j).value for j in range(1, 8)] for i in range(2, w9_max)])

# Convert Sheet B to a numpy array
data10 = np.array([[worksheet10.cell(row=i, column=j).value for j in range(1, 20)] for i in range(2, w10_max)])

# Perform the matching operation
for row9 in data9:
    temp9 = row9[0]
    for row10 in data10:
        temp10 = row10[0]
        if temp9 == temp10:
            row9[6] = row10[18]
            break

# Save the updated data back to Sheet A
for i, row9 in enumerate(data9):
    for j, value in enumerate(row9):
        worksheet9.cell(row=i+2, column=j+1).value = value

workbook9.save('output.xlsx')
```

These are just a few examples of how you can improve the performance when matching data between Excel sheets using Python. Remember to adjust the code based on your specific column names, ranges, and requirements.

TOP

最快既方法:pip install pandas

TOP

回覆 3# ych2


    pandas是最快,學埋其它方法都沒壞,學多樣野。

TOP

本帖最後由 bongbong3481 於 2023-9-6 19:38 編輯

回覆 2# s20012797

我試左numpy,  將資料load完 excel 然後load入numpy用了很長時間,4分鐘都未load完。

目前我的程度,只識用list 當array 咁用(code 下面, ‘’= ‘’前面吾知點解沒左[i]),不過都要用pandas load 資料同埋處理list  (主要是未google到load excel 去list既方法) ,用既時間大約3分鐘,1半是load 資料用既時間,1半是for loop用既時間。

import pandas as pd
df1 = pd.read_excel('A.xlsx')
df2 = pd.read_excel('B.xlsx')

list1=list(df1['Col1'])
list4=[None] * len(list1)

list2=list(df2['ColA'])
list3=list(df2['COLG'])

for i in range(10000):
                for c in range(150000):              
                                if list1==list2[c]:                                             
                                          list4 = list3[c]
                                          break

df1['new_col'] = list4
df1.to_excel('output.xlsx', index=False,columns=["Col1","Col2","Col3","new_col"])

TOP

我今日下就得閒,你唔介意既話俾個file我試試~

TOP

回覆 6# ych2


    公司野,吾出得街啊

TOP

https://ithelp.ithome.com.tw/articles/10200433
唔知幫唔幫到你,唔洗用FOR都做到~~

TOP

回覆 8# ych2

其實我系用pandas 解決左,但想學多樣,因為用黎做mapping 既column ,大部分是數字,小部份是英文加數字,用pandas 處理時,好易出現floating error

TOP