강의 문제를 in list로 푸는 경우의 시간복잡도를 O(n^3)라고 하셨습니다. 잘 이해가 가지 않아 질문드립니다. for loop로 n개의 nums 모든 요소 순회 => O(n) list에 대한 in 연산 수행 => O(n) 최소 한 번은 수행 2번 이상의 경우 while문에서 시간복잡도 계산 in 연산 수행의 반복을 while문으로 수행 worst case => O(n) [1, 2, 3, 4]의 경우 n-1, n-2, n-3, n-4번 수행 이걸 O(n)으로 취급하는건가요? 1. nums의 모든 요소에 대해 항상 while문이 O(n)으로 동작하지 않고 최악의 경우에도 n-1, n-2, n-3, ... 1로 줄어들지 않나요...? 아니면, 2. for loop로 n번 순회하면서 while loop는 n-1, n-2, n-3번 수행하게되니 두 반복문에 의한 시간복잡도는 등차수열 합의 공식에 근거해 최종적으로 O(n^2)가 되고 이 때 매번 반복하는 in연산도 O(n)이니 최종 시간복잡도는 O(n^3)다. 로 이해하는건가요? 19:47 설명 중 어떻게 while이 모든 경우에 n번 수행될 수 있는건지 궁금합니다...
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 어쩔때 sum(df) 이런식으로 sum 안에 넣을 때도 있고. 어쩔 땐 .sum()으로 표현하던데 둘의 차이가 무엇인가요?
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 5회 회귀 문제에서요! 평가 지표로 rmse를 사용하는데 함수를 사용하지 않고 rmse를 쓰려면 코드를 from sklearn.metrics import mean_squared_error mse = mean_squared_error(y_val, pred) print(mse ** 0.5) 이렇게 작성해주면 될까요?
안녕하세요 선생님, 회귀에서 분류와 예측 유형으로 나뉘는데 분류에서는 모델을 만들 떄 아래처럼 예측 시 predict_proba를 활용하고 분류 문제가 아니면 proba를 뺴게 되나요 ?? 문제에서 y값은 0 또는 1 , 또는 확률값일 떄 proba 그 외 y값이 수치형이면 proba 뺴고..제가 생각 하는게 맞을까요 ? from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier() rf.fit(X_tr[cols], y_tr) pred=rf.predict_proba(X_val[cols]) roc_auc_score(y_val,pred[:,1])
[문제] city와 f4를 기준으로 f5의 평균값을 구한 다음, f5를 기준으로 상위 7개 값을 모두 더해 출력하시오 . (소수점 둘째자리까지 출력) import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic1.csv") df.head() # city와 f4별 f5의 평균 값 (멀티인덱스 출력) df = df.groupby(['city', 'f4'])[['f5']].mean() print(df) # dataframe 전환 후 상위 7개 출력 df = df.reset_index().sort_values('f5', ascending=False).head(7) print(df) 위에는 문제와, 선생님이 작성해주신 코드입니다.! 다름아니라 제가 궁금한건 다음과 같이 두 가지입니다! # city와 f4별 f5의 평균 값 (멀티인덱스 출력) df = df.groupby(['city', 'f4'])[['f5']].mean() 첫번째, 여기서 'f5'에 []를 한번 더 쓰신 이유가 데이터프레임형태로 만들기 위해서 쓰신걸까요? 두번째, 내림차순정렬 (sort_values)를 쓰기 위해서는 데이터프레임 형태가 되야해서 첫번째에서 'f5'에 []를 한번 떠 쓰셔서 일부러 데이터프레임형태를 만드신걸까요?
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 범주형 데이터에 대한 원핫인코딩을 진행할 때 cols= train.select _dtypes(include="O").columns train=pd.get_dummies(train,columns=cols)로 진행해야 하진 않나요? train=pd.get_dummies(train)이어도 범주형만 알아서 찾아서 원핫인코딩을 진행 해주나요?
네이버 쇼핑 크롤링 1 강의를 수강하고 있습니다. 네이버 쇼핑 페이지에서 상품에 대한 태그를 추출함에 있어서 items에 데이터가 전혀 저장되지 않습니다. 코드도 완전히 동일한 것 같은데 어떤 문제가 있는 걸까요? from bs4 import BeautifulSoup import requests keyword = input("검색할 제품을 입력하세요 : ") url = f"https://search.shopping.naver.com/search/all?query={keyword}" user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36" headers = {"User-Agent" : user_agent} req = requests.get(url, headers=headers) html = req.text soup = BeautifulSoup(html, 'html.parser') items = soup.select(".adProduct_item__1zC9h") print(items) print(len(items)) 다음과 같이 []와 0만 출력되는 상황입니다.
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 안녕하세요! 2번문제에서 저는 df['bmi']로 새로운 bmi 컬럼을 만들지 않고 바로 bmi라는 변수에 넣어서 그냥 bmi를 가지고 했는데 상관없나요? bmi = df['Weight'] / (df['Height'] / 100) ** 2 cond1 = bmi >= 18.5 cond2 = bmi < 23 normal = len(df[cond1 & cond2]) cond3 = bmi >= 23 cond4 = bmi < 25 danger = len(df[cond3 & cond4]) print(int(abs(normal - danger))) 이렇게 했습니다.
구글링을 통해 pip upgrade, scipy==1.12.0 버전설치 vscode vswhere.exe 설치등을 해 보았는데 해결이 안되어 문의드립니다. (desktop_venv) D:\voicechat\DESKTOP>pip install scipy WARNING: Ignoring invalid distribution - (d:\voicechat\desktop\desktop_venv\lib\site-packages) WARNING: Ignoring invalid distribution -ip (d:\voicechat\desktop\desktop_venv\lib\site-packages) Collecting scipy Using cached scipy-1.13.1.tar.gz (57.2 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [21 lines of output] + meson setup C:\Users\joon\AppData\Local\Temp\pip-install-uhszo9tp\scipy_fd7942d271b54ed8b7897408b2e63822 C:\Users\joon\AppData\Local\Temp\pip-install-uhszo9tp\scipy_fd7942d271b54ed8b7897408b2e63822\.mesonpy-_ppx3dkm -Dbuildtype=release -Db_ndebug=if-release -Db_vscrt=md --native-file=C:\Users\joon\AppData\Local\Temp\pip-install-uhszo9tp\scipy_fd7942d271b54ed8b7897408b2e63822\.mesonpy-_ppx3dkm\meson-python-native-file.ini The Meson build system Version: 1.4.1 Source dir: C:\Users\joon\AppData\Local\Temp\pip-install-uhszo9tp\scipy_fd7942d271b54ed8b7897408b2e63822 Build dir: C:\Users\joon\AppData\Local\Temp\pip-install-uhszo9tp\scipy_fd7942d271b54ed8b7897408b2e63822\.mesonpy-_ppx3dkm Build type: native build Project name: scipy Project version: 1.13.1 WARNING: Failed to activate VS environment: Could not parse vswhere.exe output ..\meson.build:1:0: ERROR: Unknown compiler(s): [['icl'], ['cl'], ['cc'], ['gcc'], ['clang'], ['clang-cl'], ['pgcc']] The following exception(s) were encountered: Running icl "" gave "[WinError 2] 지정된 파일을 찾을 수 없습니다" Running cl /? gave "[WinError 2] 지정된 파일을 찾을 수 없습니다" Running cc --version gave "[WinError 2] 지정된 파일을 찾을 수 없습니다" Running gcc --version gave "[WinError 2] 지정된 파일을 찾을 수 없습니다" Running clang --version gave "[WinError 2] 지정된 파일을 찾을 수 없습니다" Running clang-cl /? gave "[WinError 2] 지정된 파일을 찾을 수 없습니다" Running pgcc --version gave "[WinError 2] 지정된 파일을 찾을 수 없습니다" A full log can be found at C:\Users\joon\AppData\Local\Temp\pip-install-uhszo9tp\scipy_fd7942d271b54ed8b7897408b2e63822\.mesonpy-_ppx3dkm\meson-logs\meson-log.txt [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details.
df = df[ df['year']== 2023 ] cond1 = (df['year'] > 2023) 이 어떤게 다른걸까요? df = df[ df['year']== 2023 ] 는 조건을 df에 다시 넣고 cond1 = (df['year'] > 2023) 는 조건을 df에 넣지 않고 cond1로 넣은건데요 구분이 되지 않습니다 ㅠㅠ 예를들어 cond1 = (df['year'] > 2023) 가 아닌 cond1 = df[df['year'] > 2023] 로 했을때도 가능한건지 궁금합니다.
[문제] 주어진 데이터에서 상위 10개 국가의 접종률 평균과 하위 10개 국가의 접종률 평균을 구하고, 그 차이를 구해보세요 . (단, 100%가 넘는 접종률 제거, 소수 첫째자리까지 출력) import pandas as pd df = pd.read _csv('../input/covid-vaccination-vs-death/covid-vaccination-vs-death_ratio.csv') #시간에 따라 접종률이 점점 올라감 df2 = df.groupby('country').max() df2 = df2.sort_values(by='ratio', ascending = False) #100%가 넘는 접종률 제거 cond = df2['ratio'] <= 100 df2 = df2[cond] top = df2['ratio'].head(10).mean() bottom = df2['ratio'].tail(10).mean() print(round(top - bottom,1)) 문제와 정답코드는 위와 같이 적어주셨는데, 여기서 #시간에 따라 접종률이 점점 올라감 df2 = df.groupby('country').max() 이 말의 뜻과, 코드가 이해가 되지 않습니다.
안녕하세요. 강의와는 무관한 질문이지만 본 강의 수강 완료 후 혼자서 프로젝트를 하고 있습니다. 현재 구글 리뷰 크롤링 & 스크랩중인데요. 해당 에러가 발생하는 이유를 도무지 찾을 수 가 없어서 질문 드립니다... 여러 사이트를 크롤링 해보고 엑셀을 생성 해 보았지만 왜 이런 에러가 발생하는지 로그를 봐도 제대로 표시가 안되니깐 찾기가 힘드네요. 구글 리뷰 사이트만 20여개 스크랩 했었고 엑셀도 제대로 생성 되었으니 스크랩 코드 자체에는 문제가 없는거 같습니다. 다만 이 부분에서만 문제가 생깁니다. ### 에러 발생 로그 [2024-06-12 09:42:59,954] [ERROR utils.py:179] >> Traceback (most recent call last): File "scraper\scrap_crawlers.py", line 1365, in get_review_details File "scraper\utils.py", line 202, in create_xlsx_file File "scraper\utils.py", line 181, in create_xlsx_file File "pandas\util\_decorators.py", line 333, in wrapper File "pandas\core\generic.py", line 2417, in to_excel File "pandas\io\formats\excel.py", line 952, in write File "pandas\io\excel\_openpyxl.py", line 490, in write cells File "openpyxl\cell\cell.py", line 218, in value File "openpyxl\cell\cell.py", line 197, in bind value File "openpyxl\cell\cell.py", line 165, in check_string openpyxl.utils.exceptions.IllegalCharacterError: 동생한테추천받았는데이렇게편한어플이있다니너무좋아요.현금비율은좋지않지만 신경많이안써도되서괜찮네요~ cannot be used in worksheets. During handling of the above exception, another exception occurred: ### cannot be used in worksheets. 이놈이 말썽이네요... 아래와 같이 테스트 케이스 만들어서 적용했을 때는 제대로 작동했었습니다. import asyncio from scraper.utils import create_xlsx_file, save_to_xlsx DEFAULT_NAME = "test" async def main(): data = { "message": "동생한테추천받았는데이렇게편한어플이있다니너무좋아요.현금비율은좋지않지만 신경많이안써도되서괜찮네요~" } xlsx_file = await create_xlsx_file( data, file_name=DEFAULT_NAME, sheet_name=DEFAULT_NAME ) await save_to_xlsx(xlsx_file, DEFAULT_NAME) asyncio.run(main()) # utils.py # 엑셀 가로 폭 조정하는 함수 async def calculate_dimension(worksheet: Worksheet) -> None: try: for column_cells in worksheet.iter_cols(): length = max(len(str(cell.value)) for cell in column_cells) adjusted_width = (length + 2) * 1.2 # 조정된 폭 계산 column_letter = get_column_letter(column_cells[0].column) worksheet.column_dimensions[column_letter].width = adjusted_width except Exception as e: message = f"엑셀 폭 조정 중에 예외 발생: '\n{e}" logger = await get_logger() logger.error(message) print(message) raise e # 엑셀에 서식 스타일 지정하는 함수 async def cell_pattern_fill( df: pd.DataFrame, worksheet: Worksheet, head_fill_color: str = "4472C4", head_font_color: str = "FFFFFF", body_fill_color: str = "D9E1F2", body_font_color: str = "000000", head_border_color: str = "2E5C99", body_border_color: str = "B4C6E7", fill_type: fills = "solid", ) -> None: try: # Define border styles thin_border_head = Border( left=Side(border_style="thin", color=head_border_color), right=Side(border_style="thin", color=head_border_color), top=Side(border_style="thin", color=head_border_color), bottom=Side(border_style="thin", color=head_border_color), ) thin_border_body = Border( left=Side(border_style="thin", color=body_border_color), right=Side(border_style="thin", color=body_border_color), top=Side(border_style="thin", color=body_border_color), bottom=Side(border_style="thin", color=body_border_color), ) # Set header row style for row in worksheet.iter_rows( min_row=1, max_row=1, min_col=1, max_col=df.shape[1] ): for cell in row: cell.fill = PatternFill( start_color=head_fill_color, end_color=head_fill_color, fill_type=fill_type, ) cell.font = Font(color=head_font_color, bold=True) cell.border = thin_border_head # Set body row style for i, row in enumerate( worksheet.iter_rows( min_row=2, max_row=worksheet.max_row, min_col=1, max_col=df.shape[1] ) ): for cell in row: if i % 2 == 0: cell.fill = PatternFill( start_color=body_fill_color, end_color=body_fill_color, fill_type=fill_type, ) cell.font = Font(color=body_font_color) cell.border = thin_border_body except Exception as e: message = f"엑셀 서식 지정 중에 예외 발생: '\n{e}" logger = await get_logger() logger.error(message) print(message) raise e # 본 강의 drf 엑셀 생성 파트를 참고해서 만든 엑셀 생성 함수 async def create_xlsx_file( data: Union[Dict, List], file_name: str = DEFAULT_DIR_NAME, sheet_name: str = DEFAULT_DIR_NAME, ) -> BytesIO: df = pd.json_normalize(data) io = BytesIO() io.name = file_name try: writer = pd.ExcelWriter(io, engine="openpyxl") # noqa df.to_excel( writer, index=False, engine="openpyxl", sheet_name=sheet_name, ) workbook = writer.book worksheet = workbook.active tasks = [ calculate_dimension(worksheet), cell_pattern_fill(df, worksheet), ] await tqdm.gather(*tasks, desc=f" 엑셀 파일 생성중") writer._save() # noqa except Exception as e: message = f"엑셀 생성 중에 예외 발생: '\n{e}" logger = await get_logger() logger.error(message) print(message) raise e io.seek(0) return io # 엑셀 저장 함수 async def save_to_xlsx( xlsx_file: BytesIO, dirname: str = DEFAULT_DIR_NAME, ): output_path = BASE_DIR / "스크랩_결과" / "엑셀" / dirname output_path.mkdir(parents=True, exist_ok=True) now = datetime.datetime.now() timestamp = now.strftime("%Y-%m-%d_%H_%M") filename = f"{xlsx_file.name}_{timestamp}" extension = ".xlsx" file_path = output_path / (filename + extension) try: async with aiofiles.open(file_path, "wb") as f: await f.write(xlsx_file.getvalue()) except Exception as e: message = f"엑셀 파일 저장 중에 예외 발생: '{filename}'\n{e}" logger = await get_logger() logger.error(message) print(message) raise e 전체적인 함수는 위와 같으며 엑셀 생성 중에 에러가 발생하였으니 create_xlsx_file 함수 부분에서 해결을 해보아야 할것 같습니다. 아니면 혹시 엑셀의 행을 생성 중에 에러가 발생하였을 때 해당 행은 스킵하고 이어서 진행하게 하는 방법이 있을까요?? "raise e"을 발생 시키지 않아도 엑셀 생성 작업 스킵이 되지않고 작업 자체에 문제가 생기네요
안녕하세요 선생님 저는 작업형 2를 아래와 같은 매커니즘으로 푸려고 합니다. train.info()를 통해서 object 컬럼 확인 → 만약 범주형 데이터가 있다면? → 라벨인코딩 (여기서 cols = train.select_dtypes(include='object').columns 로 해서 푸려고 합니다.) → target = train.pop('타겟컬럼') train = train.drop('ID',axis=1) test_ID = test.pop('ID') → train_test_split을 통해 검증데이터 분리 train_test_split(train, target, test_size=0, random_state=0) <여기서 train과 target으로만 쓰기 위해서 위에서 pop과 drop을 진행했습니다.> → 모델 예측 및 검증 무조건 랜덤포레스트로 진행하고 그 후에 하이퍼파라메터 튜닝으로 성능 비교해볼 생각입니다. → 평가지표에 따른 성능 비교 → 하이퍼파라메터 튜닝 적용해보기 → DataFrame 만들기 → csv만들기 매커니즘에 따른 코드는 다음과 같습니다. train.info () from sklearn.preprocessing import LabelEncoder cols = train.select_dtypes(include='object').columns for col in cols: le = LabelEncoder() train[col] = le.fit_transform(train[col]) test[col] = le.transform(test[col]) target = train.pop('타겟컬럼') train = train.drop('ID',axis=1) test_ID = test.pop('ID') from sklearn.model_selection import train_test_split X_tr, X_val, y_tr, y_val = train_test_split(train, target, test_size=0, random_state=0) from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(random_state=0, max_depth = 5, n_estimators = 500) rf.fit(X_tr,y_tr) pred = rf.predict(X_val) from sklearn.metrics import f1_score print(f1_score(y_val, pred, average='macro')) pred = rf.predict(test) submit = pd.DataFrame({ 'ID' : test_ID, '타겟컬럼' : pred }) submit.to_csv('0000.csv', index=False) 여기서 질문은 1. pop과 drop을 저 단계에서 해줘도 무방한가요? cols를 라벨 인코딩에서 먼저 정의해주게 되는데 그 이후에 pop과 drop써도 무방한지 여쭤봅니다. 2. 물론 어떤 데이터를 주냐에 따라 다르겠지만 위와 같은 과정으로 진행해도 점수획득에 큰 무리 없겠죠? (교차검증등등은 진행하고 싶지 않아서요) 3. 범주형 데이터가 하나도 없다면? 그럴일이 없을거 같긴한대 그러면 인코딩단계만 빼고 그대로 진행하면되나용?