Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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 31
Tags
more
Archives
Today
Total
관리 메뉴

철솜_STUDY

Python 문법 정리 _ ongoing~ 본문

Self-Taught

Python 문법 정리 _ ongoing~

CC_flavor.철근 2024. 9. 29. 14:32
import seaborn as sns                   #시각화 패키지
import matplotlib.pyplot as plt         #시각화 패키지
import pandas as pd


sns.set(color_codes=True)
%matplotlib inline

*sns.set(color_codes=True):

  • Seaborn의 색상 설정을 활성화합니다. color_codes=True로 설정하면, 기본 색상 코드가 Seaborn의 색상 팔레트와 일치하도록 설정됩니다.

* %matplotlib inline:

  • 주피터 노트북(Jupyter Notebook)**에서 그래프를 화면에 바로 출력하기 위해 사용하는 명령어입니다. 이 명령어를 사용하면, 그래프를 그릴 때마다 별도의 명령 없이 바로 노트북 안에 그래프가 표시됩니다. 주피터 노트북에서만 사용하는 특수한 명령어입니다. 스크립트 환경에서는 불필요한 명령어
df.info()

DataFrame.info() _ 자료 내 칼럼명, 속성, 결측치 여부 확인. 

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 119390 entries, 0 to 119389
Data columns (total 32 columns):
 #   Column                          Non-Null Count   Dtype  
---  ------                          --------------   -----  
 0   hotel                           119390 non-null  object 
 1   is_canceled                     119390 non-null  int64  
 2   lead_time                       119390 non-null  int64  
 3   arrival_date_year               119390 non-null  int64  
 4   arrival_date_month              119390 non-null  object 
 5   arrival_date_week_number        119390 non-null  int64  
 6   arrival_date_day_of_month       119390 non-null  int64  
 7   stays_in_weekend_nights         119390 non-null  int64  
 8   stays_in_week_nights            119390 non-null  int64  
 9   adults                          119390 non-null  int64  
 10  children                        119386 non-null  float64
 11  babies                          119390 non-null  int64  
 12  meal                            119390 non-null  object 
 13  country                         118902 non-null  object 
 14  market_segment                  119390 non-null  object 
 15  distribution_channel            119390 non-null  object 
 16  is_repeated_guest               119390 non-null  int64  
 17  previous_cancellations          119390 non-null  int64  
 18  previous_bookings_not_canceled  119390 non-null  int64  
 19  reserved_room_type              119390 non-null  object 
 20  assigned_room_type              119390 non-null  object 
 21  booking_changes                 119390 non-null  int64  
 22  deposit_type                    119390 non-null  object 
 23  agent                           103050 non-null  float64
 24  company                         6797 non-null    float64
 25  days_in_waiting_list            119390 non-null  int64  
 26  customer_type                   119390 non-null  object 
 27  adr                             119390 non-null  float64
 28  required_car_parking_spaces     119390 non-null  int64  
 29  total_of_special_requests       119390 non-null  int64  
 30  reservation_status              119390 non-null  object 
 31  reservation_status_date         119390 non-null  object 
dtypes: float64(4), int64(16), object(12)
memory usage: 29.1+ MB

 

#특정 데이터 프레임 속 정보를 한 번에 정리해주는 dataFrame['칼럼 명'].value_counts()

df['meal'].head(10)
df['meal'].info()     #데이터 프레임 칼럼 속 정보를 한 번에 정리해주는 그런건 없을까? 

df['meal'].value_counts()
<class 'pandas.core.series.Series'>
RangeIndex: 119390 entries, 0 to 119389
Series name: meal
Non-Null Count   Dtype 
--------------   ----- 
119390 non-null  object
dtypes: object(1)
memory usage: 932.9+ KB
meal
BB           92310
HB           14463
SC           10650
Undefined     1169
FB             798
Name: count, dtype: int64

 

#데이터 필터링 by 자료형

numeric_df = df.select_dtypes(include=['float64', 'int64'])

1. 기본 데이터 타입

  • include나 exclude에 다음과 같은 데이터 타입을 사용할 수 있습니다:
  • 'float', 'float64': 실수형 데이터
  • 'int', 'int64': 정수형 데이터
  • 'number': 모든 수치형 데이터(int + float)
  • 'object': 문자열 또는 범주형 데이터
  • 'bool': 논리형 데이터 (True, False)
  • 'datetime': 날짜/시간형 데이터 (datetime64)
  • 'timedelta': 시간 간격형 데이터 (timedelta64)
  • 'category': 범주형 데이터
  • 'complex': 복소수형 데이터
 
 

#to_datetime() 함수

pd.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', cache=True)

주요 매개변수 및 옵션 설명:

  1. arg:
    • 변환하려는 입력 데이터로, 문자열, 숫자, datetime 객체, 리스트 또는 Series 형태로 입력할 수 있습니다.
    • 예: "2023-10-01", ["2023-10-01", "2024-05-12"], [1693545600, 1694137600] (유닉스 타임스탬프)
  2. errors ({'raise', 'coerce', 'ignore'}):
    • 입력 데이터 변환 시 오류 발생 시의 동작을 지정합니다.
    • 기본값: 'raise'
    • 옵션:
      • 'raise': 오류 발생 시 예외를 발생시킵니다.
      • 'coerce': 오류가 발생한 데이터를 NaT (Not-a-Time)으로 표시합니다.
      • 'ignore': 오류 발생 시 무시하고 원래 데이터를 그대로 반환합니다.
  3. dayfirst (bool):
    • 날짜 형식에서 day/month/year 형식으로 해석할지를 결정합니다.
    • 기본값: False (즉, month/day/year로 해석)
    • 예: dayfirst=True이면 01/02/2023는 2월 1일로 해석되고, False면 1월 2일로 해석됩니다.
  4. yearfirst (bool):
    • 날짜 형식에서 연도를 우선적으로 해석할지를 결정합니다.
    • 기본값: False
    • 예: yearfirst=True이면 2023-10-01을 연-월-일로 인식합니다.
  5. utc (bool or None):
    • 변환된 datetime이 UTC 타임존으로 표시될지 여부를 설정합니다.
    • 기본값: None
    • True로 설정하면 결과가 UTC로 변환됩니다.
  6. format (str):
    • datetime을 파싱할 때 사용할 날짜/시간 형식을 명시합니다.
    • 기본값: None
    • 형식 문자열(예: "%Y-%m-%d %H:%M:%S")을 지정하여 입력 데이터를 빠르게 변환할 수 있습니다.
    • 예: format="%Y-%d-%m"이면 2023-01-02는 2월 1일 2023년으로 해석됩니다.
  7. exact (bool):
    • format이 지정된 경우, 입력 문자열이 정확히 해당 형식과 일치해야 하는지 여부를 설정합니다.
    • 기본값: True
    • True면 형식과 정확히 일치해야 하고, False면 형식이 부분적으로 일치해도 변환을 시도합니다.
  8. unit (str):
    • 숫자형 데이터(arg)의 단위를 설정합니다.
    • 기본값: None
    • 예: "s" (초), "ms" (밀리초), "us" (마이크로초), "ns" (나노초) 등으로 설정하여, 숫자를 해당 단위의 시간값으로 변환합니다.
    • 예: pd.to_datetime([1693545600, 1694137600], unit='s')은 유닉스 타임스탬프를 datetime으로 변환합니다.
  9. infer_datetime_format (bool):
    • format이 명시되지 않은 경우, 데이터의 형식을 자동으로 추론하여 변환 속도를 높일지를 설정합니다.
    • 기본값: False
    • True로 설정하면 자동으로 데이터 형식을 추정하여 변환할 때의 성능이 개선될 수 있습니다.
  10. origin ({'unix', 'julian', datetime-like}):
    • 숫자형 데이터를 datetime으로 변환할 때 기준이 되는 날짜를 설정합니다.
    • 기본값: 'unix' (1970-01-01)
    • julian (율리우스 날짜) 또는 특정 날짜("yyyy-mm-dd" 형식의 문자열 또는 datetime 객체)로 설정할 수 있습니다.
  11. cache (bool):
    • 동일한 입력 값이 반복적으로 사용될 경우 캐싱을 사용하여 변환 속도를 향상시킬지를 설정합니다.
    • 기본값: True
    • True로 설정하면 캐시가 활성화되어 변환이 더 빠르게 이루어질 수 있습니다

## datetime method에서 혼합이 돼 있을 경우 format='mixed'라는 옵션 사용 가능, dayfirst=True라는 옵션도 같이 넣기)

> infer_datetime_format 이 더이상 권장 사용되지 않는다! 
df['Date2'] = pd.to_datetime(df['Order Date'], format='mixed', dayfirst=True)


df = df.sort_values(by='Date2')
df['Year'] = df['Date2'].dt.year
df.head()