일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 함수
- 맛집
- port
- 다이어트
- ubuntu
- node.js
- flutter
- Unity
- 날짜
- javascript
- swift
- MS-SQL
- pandas
- 유니티
- Linux
- GIT
- python
- sqlite
- mssql
- ASP
- IOS
- 라즈베리파이
- PyQt
- urllib
- 리눅스
- Excel
- MySQL
- PyQt5
- PER
- tensorflow
목록랭귀지/pandas (111)
아미(아름다운미소)
import pandas as pd# Parquet 파일 읽기df = pd.read_parquet('example.parquet')# 전체 데이터 출력print("전체 데이터:")print(df)# 상위 5행 출력print("\n상위 5행:")print(df.head())# 데이터 구조 확인print("\n데이터 구조:")print(df.info())# 기술 통계 정보print("\n기술 통계:")print(df.describe())
예제1import pandas as pd# --------------------------------------------# 1. 샘플 데이터 생성# --------------------------------------------df = pd.DataFrame({ 'a': [1, 2, 3, 4], 'b': ['A', 'B', 'C', 'D'], 'c': [10, 20, 30, 40]})df2 = pd.DataFrame({ 'a': [1, 2, 3, 5], 'b': ['A', 'X', 'C', 'E'], 'c': [10, 20, 30, 50]})# --------------------------------------------# 2. 비교 방법 구현# ------------..
최적화 최존def process_dataframe_optimized(dict_df_types, df): type_handlers = { 'int': lambda s: pd.to_numeric(s, errors='coerce').fillna(0).astype('int32'), 'float': lambda s: pd.to_numeric(s, errors='coerce').fillna(0).astype('float32'), # float32로 변경 'bool': lambda s: s.astype(str).str.lower().isin(['true', 't', '1']), # 더 넓은 불리언 조건 'datetime': lambda s: pd.to_dat..
# 날짜 변환 (NULL → NaT)dates = pd.to_datetime(df['a'], errors='coerce')if not dates.empty and not pd.isna(dates.iloc[0]): first_date = dates.iloc[0]else: first_date = pd.to_datetime('today') # 기본값 설정
index.duplicated() 메서드 사용# 중복된 인덱스 위치 확인duplicated = df.index.duplicated(keep='first') # 첫 번째 발생은 False, 이후 중복은 Trueprint(duplicated)# 출력: [False False True False]# 중복된 인덱스 값 확인duplicated_values = df.index[df.index.duplicated()]print(duplicated_values)# 출력: Index(['b'], dtype='object')value_counts()로 중복 횟수 확인# 각 인덱스 값의 발생 횟수 확인index_counts = df.index.value_counts()print(index_counts)# 출력:# b ..
import pandas as pdfrom pandas_profiling import ProfileReport# 1. 데이터프레임 준비 (예시)df = pd.read_csv("your_data.csv")# 2. 프로파일링 리포트 생성 → 가장 먼저 실행!profile = ProfileReport(df, explorative=True)# 3. (선택사항) 추가 설정 (예: 제목 변경, 변수 조정)profile.set_variable("title", "My Custom Report")# 4. 최종 저장 → 마지막에 실행!profile.to_file("report.html")from pandas_profiling import ProfileReportprofile = ProfileReport(df, explo..
def analyze_memory_usage(df, warning_threshold=20): """ [최종 개선사항] 1. drop() 메서드 오류 해결 2. 인덱스/컬럼 처리 강화 3. 메모리 계산 최적화 """ try: # 1. 메모리 사용량 계산 mem_usage = df.memory_usage(deep=True) total_memory = mem_usage.sum() # 2. 분석 결과 생성 mem_analysis = pd.DataFrame({ 'Memory (MB)': (mem_usage / (1024**2)).round(2), 'Percent..
import pandas as pdimport numpy as np# 예시 데이터 (NaN 포함)df1 = pd.DataFrame({'A': [1, 2, np.nan], 'B': ['a', 'b', 'c']}, index=[0, 1, 2])df2 = pd.DataFrame({'A': [1, 2, 4], 'B': ['a', 'x', np.nan]}, index=[1, 2, 3])# 1. merge 실행 (outer join)merged = pd.merge( df1.reset_index(drop=True), df2.reset_index(drop=True), how='outer', indicator='_source', on=list(df1.columns), suffixes..
import pandas as pdimport numpy as npfrom typing import Optionaldef memory_optimizer( df: pd.DataFrame, enable_category: bool = True, enable_downcast: bool = True, safe_mode: bool = True, verbose: bool = True) -> pd.DataFrame: """ 데이터 정확성을 보장하는 메모리 최적화 함수 Parameters: df: 입력 DataFrame enable_category: 문자열 범주형 변환 활성화 (기본 True) enable_downcast: 숫자형 다..
# 기존 메모리 사용량 확인df.info(memory_usage='deep')# 정수형 컬럼 최적화int_cols = df.select_dtypes(include=['int64']).columnsdf[int_cols] = df[int_cols].apply(pd.to_numeric, downcast='integer')# 실수형 컬럼 최적화float_cols = df.select_dtypes(include=['float64']).columnsdf[float_cols] = df[float_cols].apply(pd.to_numeric, downcast='float')# 문자열 컬럼은 범주형으로 변환 (고유값이 적은 경우)obj_cols = df.select_dtypes(include=['object']).co..