✏️ 24.12.20 TIL

Dada·2024년 12월 21일

📅 TO DO


  • QCC 2회차 시험
  • PANDAS 라이브세션
  • 데이터시각화 라이브세션

📝 MEMO


▶ Pandas 라이브 세션

1. 함수 처리

1) apply()

  • 복잡한 조건을 정의할 때 사용
  • df.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)
  • axis : {0 또는 index / 1 또는 columns} 함수를 적용할 축. axis=0 의 경우 각각의 column에 함수를 적용. axis=1의 경우, 각각의 row에 함수를 적용
# 복잡한 조건문을 짤때 이용
df = pd.DataFrame({
    'value': [10, 20, 30],
    'operation': ['square', 'double', 'negate']
})

# operation 값에 따라 계산
def perform_operation(row):
    if row['operation'] == 'square':
        return row['value'] ** 2
    elif row['operation'] == 'double':
        return row['value'] * 2
    elif row['operation'] == 'negate':
        return -row['value']

df['result'] = df.apply(perform_operation, axis=1)

# 사실 아래처럼 코드를 짜도 결과는 같다...
df['result'] = -df['value']
df.loc[df['operation']=="double", "result"] = df["value"] * 2
df.loc[df['operation']=="square","result"] = df["value"] ** 2

2) lamda

  • lambda익명 함수를 정의할 때 사용하는 파이썬의 기능
  • 간단한 작업을 처리하기 위한 짧은 함수로 활용
  • 일반적인 def 함수와 달리 이름이 없고, 한 줄로 표현
  • lambda 매개변수: 반환값
def add(x, y):
	return x+y

print(add(3,5))
	
# 두 숫자를 더하는 람다 함수
add2 = lambda x, y: x + y
print(add2(3, 5))  # 출력: 8

# apply(lambda) 사용 예시 1
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

# 각 요소에 10을 더하기
result = df.apply(lambda x: x + 10)
print(result)

# apply(lambda) 사용 예시 2
df = pd.DataFrame({
    'first_name': ['John', 'jane', 'alice'],
    'last_name': ['Doe', 'Smith', 'Brown'],
    'age': [25, 30, 28]
})

df['first_name'].apply(lambda x:any(c.isupper() for c in x))
# True, False, False

2. 그룹화 / 피봇팅

1) 그룹화 groupby()

  • groupby()는 데이터를 피봇팅하여 통계량을 볼 수 있도록 도와주는 메서드
  • 데이터를 특정 조건에 맞게 전처리해 줄 때 용이
  • df.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=NoDefault.no_default, observed=False, dropna=True)
  • by : 그룹화할 내용. 함수, 축, 리스트 등등이 올 수 있음
# !pip install seaborn
import seaborn as sns
df = sns.load_dataset("titanic")
df.groupby('sex').mean()

# 성별, 좌석등급 별 통계
df.groupby(['sex', 'pclass']).mean()

# 성별, 좌석등급 별  survived 컬럼 통계
df.groupby(['sex', 'pclass'])['survived'].mean()

# DataFrame으로 출력
pd.DataFrame(df.groupby(['sex', 'pclass'])['survived'].mean())

# index 초기화
df.groupby(['sex', 'pclass'])['survived'].mean().reset_index()
# 다중 컬럼 groupby
df.groupby(['sex', 'pclass'])[['survived', 'age']].mean()

# 다중 통계값
df.groupby(['sex', 'pclass'])[['survived', 'age']].agg(['mean', 'sum'])

2) 피봇팅 pivot_table()

  • pivot_table는 데이터를 스프레드시트 기반 피벗 테이블로 변환하는 메서드
  • 엑셀 스프레드시트 피벗 테이블과 유사
  • df.pivot_table(values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All', observed=False, sort=True)
  • values : 값으로 입력될 컬럼
  • index : 인덱스로 사용될 컬럼
  • columns : 열로 사용될 컬럼
  • aggfunc : 적용할 함수
  • fill_value : 결측치를 채워넣을 값
  • margins : 합계를 표시할지 여부 True일 경우 새 열을 생성하여 합계를 출력
# index에 그룹을 표기
df.pivot_table(index='who', values='survived')

# columns에 그룹을 표기
df.pivot_table(columns='who', values='survived')

df.pivot_table(index=['who', 'pclass'], values='survived')
df.pivot_table(index='who', 
							columns='pclass', 
							values='survived', 
							aggfunc=['sum', 'mean'])

3. 기초 통계

  • df.max(axis=None, skipna=None, level=None, numeric_only=None, kwargs)
  • df.min(axis=None, skipna=None, level=None, numeric_only=None, kwargs)
  • df.mean(axis=None, skipna=None, level=None, numeric_only=None, kwargs)
  • df.median(axis=None, skipna=None, level=None, numeric_only=None, kwargs)
    • axis : {0 : index / 1 : columns} 계산의 기준이 될 축
    • skipna : 결측치를 무시할지 여부
    • level : Multi Index의 경우 연산을 수행할 레벨
    • numeric_only : 숫자, 소수, bool 이용할지 여부
    • kwargs : 함수에 전달할 추가 키워드
  • df.mode(axis=0, numeric_only=False, dropna=True)
    • dropna : 결측치를 계산에서 제외할지 여부. False일 경우 결측치도 계산에 포함
  • df.std(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, kwargs)
  • df.var(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, kwargs)
    • ddof : 표본표준편차 계산의 분모가되는 자유도를 지정. 산식은 n - ddof값으로 기본값은 n-1
  • df.cumsum(axis=None, skipna=True, args, kwargs)
  • df.cumprod(axis=None, skipna=True, args, kwargs)
    • axis : 누적합/누적곱을 구할 축을 지정
    • skipna : 결측치를 무시할지 여부
  • df.quantile(q=0.5, axis=0, numeric_only=True, interpolation='linear')
    • q : 분위수. 소수로 표현 (예 : 75% = 0.75)
    • aixs : 분위수의 값을 구할 축.
    • numeric_only : 수만 대상으로할지 여부. False일 경우 datetime 및 timedelta 데이터의 분위수도 계산됨.
    • interpolation : 분위수에 값이 없을때 보간하는 방법
      • liner : i + (j - i) x 비율 [분위수 앞, 뒤 수 간격 * 비율]
      • lower : i [분위수 앞, 뒤수 중 작은수]
      • higher : j [분위수 앞, 뒤수 중 큰수]
      • midpoint : (i+j)÷2 [분위수 앞, 뒤수의 중간값]
      • nearest : i or j [분위수 앞, 뒤수중 분위수에 가까운 수]
  • df.corr(method='pearson', min_periods=1)
    • method : {pearson / kendall / spearman} 적용할 상관계수 방식
    • min_periods : 유효한 결과를 얻기위한 최소 값의 수 (피어슨, 스피어먼만 사용가능)
  • df.corrwith(other, axis=0, drop=False, method='pearson')
    • other : 동일한 이름의 행/열을 비교할 다른 객체
    • axis : {0 : index / 1 : columns} 비교할 축. 기본적으로 0으로 인덱스끼리 비교
    • drop : 동일한 이름의 행/열이 없을경우 NaN을 출력하는데, 이를 출력하지 않을지 여부

4. 시계열 데이터 처리

1) 판다스로 날짜 다루기

  • pd.to_datetime()
    • 문자열을 날짜로 생성
    • to_datetime()에 날짜들의 리스트를 넣을 경우, DatetimeIndex라는 배열이 생성
pd.to_datetime('2019-1-1 12') 
# Timestamp('2019-01-01 12:00:00') 

pd.to_datetime(['2018-1-1', '2019-1-2']) 
#DatetimeIndex(['2018-01-01', '2019-01-02'], dtype='datetime64[ns]', freq=None
  • pd.date_range()
    • 특정 기간의 날짜를 자동 생성
    • '2019-01'과 '2019-02'를 전달하면 2월 말까지 데이터를 생성하는 것이 아니라 2월 1일자 데이터만 생성
pd.date_range('2018-1-1', '2019-1-2')

"""
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
               '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08',
               '2018-01-09', '2018-01-10',
               ...
               '2018-12-24', '2018-12-25', '2018-12-26', '2018-12-27',
               '2018-12-28', '2018-12-29', '2018-12-30', '2018-12-31',
               '2019-01-01', '2019-01-02'],
              dtype='datetime64[ns]', length=367, freq='D')
"""

2) import datetime

  • 날짜와 시간을 다루기 위한 모듈로, 별도의 설치없이 import해서 쓰면 됨
  • date, time, datetime, timedelta 등 다양한 클래스를 제공
  • datetime.datetime.strptime(date_string, format)
    • 문자열로 된 날짜 및 시간을 datetime 객체로 변환
    • “string parse time”의 약자
  • datetime.datetime.strftime(format)
    • datetime 객체를 지정한 포맷에 맞게 문자열로 변환

    • “string format time”의 약자

      import datetime
      
      # 현재 시간 가져오기
      now = datetime.datetime.now()
      print("현재 시간:", now)
      
      # 날짜 및 시간 객체 생성
      dt = datetime.datetime(2022, 3, 1, 12, 30, 45)
      print("생성된 날짜 및 시간:", dt)
      
      # 문자열을 날짜 및 시간으로 변환
      str_date = "2022-03-01 12:30:45"
      dt = datetime.datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S")
      print("문자열에서 생성된 날짜 및 시간:", dt)
      
      # 날짜 및 시간 객체의 속성 접근
      year = now.year
      month = now.month
      day = now.day
      hour = now.hour
      minute = now.minute
      second = now.second
      microsecond = now.microsecond
      print(year, month, day, hour, minute, second, microsecond)
      
      # 날짜 및 시간 객체 간의 차이 계산
      delta = datetime.datetime(2022, 3, 1, 12, 30, 45) - datetime.datetime(2022, 2, 28, 11, 15, 30)
      print("두 날짜 및 시간의 차이:", delta)
      
      # 날짜 및 시간 포맷 지정
      str_date = now.strftime("%Y-%m-%d %H:%M:%S")
      print("포맷 지정된 현재 시간:", str_date)

0개의 댓글