학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 안녕하세요! 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"을 발생 시키지 않아도 엑셀 생성 작업 스킵이 되지않고 작업 자체에 문제가 생기네요
윈도우 절 코드 실습 중입니다. select product_id, product_name, category_id , unit_price , sum(unit_price) over (partition by category_id order by unit_price rows between 1 preceding and 1 following) as unit_price_sum from products; 위 코드는 제공해주신 base 코드입니다. 해당 unit_price_sum을 소수점 둘째자리 까지만 표시하고자 round 함수를 썼는데, round(sum(unit_price) over (partition by category_id order by unit_price rows between 1 preceding and 1 following), 2) as unit_price_sum from products; "SQL Error [42883]: 오류: round(real, integer) 이름의 함수가 없음 Hint: 지정된 이름 및 인자 자료형과 일치하는 함수가 없습니다. 명시적 형변환자를 추가해야 할 수도 있습니다." 이와 같은 에러가 납니다. 그래서 with절로 해당 unit_price_sum을 temp_01이라는 임시 쿼리에 담아서 아래와 같이 했지만 이래도 위 오류와 동일하게 나오면서 되지 않네요 with temp_01 as ( select avg(unit_price) over (partition by category_id order by unit_price rows between 1 preceding and 1 following) as unit_price_avg from products ) select round(temp_01.*, 2) from temp_01; select product_id, product_name, category_id, unit_price ,avg(unit_price) over (partition by category_id order by unit_price rows between 1 preceding and 1 following) as unit_price_avg from products; 하는 방법이 있을까요? chat gpt도 서브쿼리로 답을 제공했는데 동일한 문제가 발생했습니다.
안녕하세요 선생님 저는 작업형 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. 범주형 데이터가 하나도 없다면? 그럴일이 없을거 같긴한대 그러면 인코딩단계만 빼고 그대로 진행하면되나용?
onChangeContents 함수 부분에 넣었을때 처음엔 버튼이 노란색으로 변했습니다만 이후 onChangeWriter 와 onChangeTItle 부분까지 넣은 후 버튼의 색이 변하지 않습니다. if문을 다 지우고 setIsActive(true)만 넣었을때는 작동이 됩니다..
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 범주형 데이터가 있으면 필수로 인코딩을 해줘야하는걸로 알고 있는데요 이때 무조건 라벨인코딩으로 진행하려고 하는데 문제없는 사항인가요?
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 안녕하세요. 좋은 강의 감사드립니다. 오류 없이 결과는 나왔습니다. 제 코드가 맞는지, 엉뚱한지 확인이 어려워 질문드립니다. 맞는 풀이인가요? 고쳐야 할 부분이 어떤 부분인가요? ID 드랍하지 않고 쭉 진행했는데, 이러할 경우 문제가 되나요? roc_auc_score, submit 과정에서 pred에 [:,1] 을 하면 오류가 없고, 빼면 오류가 생기는데 pred[:,1]인 이유가 헷갈립니다. 랜덤포레스트에서 random_state=2024만 적어서 돌려도 되나요? 질문이 장황한데 답변 주셔서 항상 감사합니다! cols = ['Warehouse_block' ,'Mode_of_Shipment','Product_importance' , 'Gender'] from sklearn.preprocessing import LabelEncoder le = LabelEncoder() for col in cols: X_train[col] = le.fit_transform(X_train[col]) X_test[col] = le.transform(X_test[col]) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_train, y_train['Reached.on.Time_Y.N'], test_size = 0.2, random_state = 2024) from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(n_estimators=160, max_depth=20, random_state=2024) rf.fit(X_train, y_train) pred = rf.predict_proba(X_test) from sklearn.metrics import roc_auc_score print(roc_auc_score(y_test, pred[:,1])) pred = rf.predict_proba(X_test) pred submit = pd.DataFrame({ 'ID': X_test['ID'], 'pred':pred[:,1] }) submit.to_csv("result.csv", index=False) import pandas as pd df = pd.read_csv("result.csv")
안녕하세요 선생님, CLIENTNUM,Attrition_Flag 타겟 분류 문제에서, y가 분류니까 roc_auc_score을 구할 때 predict_proba를 이용해서 구했는데 from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier() model.fit(X_tr,y_tr) pred = model.predict(X_val) print(accuracy_score(y_val, pred)) # 정밀도 print(precision_score(y_val, pred)) # 재현율 (민감도) print(recall_score(y_val, pred)) # F1 print(f1_score(y_val , pred)) 정확도 ~ f1까지는 proba를 안하고 바로 구했는데 어떤 차이로 인해 얘네는 proba를 안하게 될까요 ? ㅜㅜ
선생님, 이제 한 열흘 정도 남은 상황에서 강의 보면 이해는 되는데 실제로 타이핑 치려니까 머리속이 하얘지면서 어려운데, ㅠ 앞으로 남은 기간동안은 어떤 방식으로 공부를 하는게 좋을까요? 강의를 빼곡히 노션에 정리하면서 멘트나 그런것들 정리해뒀는데... 막막하네요ㅜ.ㅜ 1유형은 캐글 반복 + 2유형 기출만 반복(1~7회) 3유형은 회귀분석이랑 분산분석 2개만 외워가려고요..ㅎ 갑갑하네요ㅜ.ㅜ 증말
문제 1-2 accuracy를 구하는 문제를 저는 다음과 같이 풀었습니다. from statsmodels.formula.api import logit model = logit('purchase~income', data=train).fit() target = test.pop('purchase') pred = model.predict(test) > 0.5 from sklearn.metrics import accuracy_score print (round(accuracy_score(target, pred),3)) 답은 0.507로 동일하게 나오는 것 같습니다. 다음과 같이 풀어도 문제 없는걸까요? 그리고 pred = model.predict(test) > 0.5에서 '>0.5'의 역할은 무엇인지 다시 한번 설명해 주실 수 있을까요?