https://question99.tistory.com/1095
[파이썬] 조건에 맞는 데이터 계산(다중 for문)
어떤 데이터가 있을때 어떤 컬럼의 데이터들끼리 어떤 조건들로 찾거나 계산할때import timeimport pandas as pdimport numpy as npnp.random.seed(0) # 난수 생성 시 일관성을 위해 시드 설정### 1) 데이터 생성data_s
question99.tistory.com
앞 코드에서 항목이 많아지면 시간이 너무 많이 소요 됨. 앞에서는 약 5분정도 소요됨.
다음과 같이 병렬처리로 실행시간 단축 함.
import itertools
import psutil
from functools import partial
import time
from joblib import Parallel, delayed
import pandas as pd
import numpy as np
np.random.seed(0) # 난수 생성 시 일관성을 위해 시드 설정
### Parallel에서 call 하는 함수. 하나의 조건만 실행
def run_simulation(idx, case1, case2, df):
count1 = []
count2 = []
for i in range(len(df)):
data1 = df[case1[0]].iloc[i]
data2 = df[case1[1]].iloc[i]
data3 = df[case2[0]].iloc[i]
data4 = df[case2[1]].iloc[i]
if data1 > data2:
count1.append(idx)
elif data3 > data4:
count2.append(idx)
count_sum = len(count1) + len(count2)
print(f"[{idx}] {case1} : {case2} : {count_sum}")
return [idx, count_sum] # 결과가 누적되로고 함
### 1) 데이터 생성
data_size = 2000
data = {
'c1': np.random.randint(50, 201, size=data_size), # 50에서 200 사이의 정수, 100개
'c2': np.random.randint(50, 201, size=data_size),
'c3': np.random.randint(50, 201, size=data_size),
'c4': np.random.randint(50, 201, size=data_size),
'c5': np.random.randint(50, 201, size=data_size),
'c6': np.random.randint(50, 201, size=data_size),
'c7': np.random.randint(50, 201, size=data_size),
'c8': np.random.randint(50, 201, size=data_size),
'c9': np.random.randint(50, 201, size=data_size),
'c10': np.random.randint(50, 201, size=data_size)
}
# DataFrame 생성
df = pd.DataFrame(data)
### 2) 조건의 조합(순열) 만들기
col = ['c1','c2','c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10']
lst = list(itertools.permutations(col, 2))
### 3) 데이터에서 조건으로 찾기. [[0, ('c1', 'c2'), ('c1', 'c2')], [1, ('c1', 'c2'), ('c1', 'c3')], [2, ('c1', 'c2'), ('c1', 'c4')]...
combinations2 = [
(idx, case1, case2)
for idx, (case1, case2) in enumerate(
[(b, s) for b in lst for s in lst]
)
]
start_time = time.time()
idx = 0
max_idx = 0
max_count = 0
# 병렬(다중) 작업. combinations에서 조건(데이터)를 하나씩 지정해서 하나의 단위 작업(함수)가 실행되도록 함
results = Parallel(n_jobs=-1)(
delayed(run_simulation)(idx, case1, case2, df)
for idx, case1, case2 in combinations2
)
best_idx, max_count = max(results, key=lambda x: x[1]) # 결과 results에 다중 작업의 각 결과가 append 되어 있음
max_info = [item for item in combinations if item[0] == best_idx]
case1 = max_info[0][1]
case2 = max_info[0][2]
# case1_col = [col[case1[0]], col[case1[1]]]
# case2_col = [col[case2[0]], col[case2[1]]]
### 4) 출력
print(f"Best case : {max_count:,} (idx={best_idx}), {case1}:{case2}")
# print(f"Best case : {max_count:,} (idx={best_idx})")
# 실행기간 계산 및 출력
end_time = time.time()
elapsed = end_time - start_time
minutes = int(elapsed // 60)
seconds = int(elapsed % 60)
print(f"\nRunning time: {minutes}m {seconds}sec")
다중 for문으로 했을때 5분에서 24 sec로 12.5배 실행속도가 개선 됨
Numba를 사용해서 속도 개선
https://question99.tistory.com/1097
[파이썬] 조건에 맞는 데이터 계산(Numba사용)
https://question99.tistory.com/1095 [파이썬] 조건에 맞는 데이터 계산(다중 for문)어떤 데이터가 있을때 어떤 컬럼의 데이터들끼리 어떤 조건들로 찾거나 계산할때import timeimport pandas as pdimport numpy as npnp.r
question99.tistory.com
https://question99.tistory.com/1098
[파이썬] 조건에 맞는 데이터 계산(병렬처리 하지 않고 Numba만 사용)
https://question99.tistory.com/1095 [파이썬] 조건에 맞는 데이터 계산(다중 for문)어떤 데이터가 있을때 어떤 컬럼의 데이터들끼리 어떤 조건들로 찾거나 계산할때import timeimport pandas as pdimport numpy as npnp.r
question99.tistory.com
댓글