달력

4

« 2024/4 »

  • 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
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 6 회차 미션 시작]

* 복습

 - concat 으로 데이터 합치기

 - 기초 통계함수와 pivot table 의 기능에 대해서 알아봤었다.

 


 

[01. Part 1) 데이터 핸들링 Chapter 04. 한 눈에 데이터 보기 - 데이터 통합 및 집계 - 05. groupby를 이용한 데이터 집계]

 

* groupby: 분할, 적용, 결합

// 적용.. 특정한 집계 함수를 사용한다고 생각하면 된다.

 - groupby 는 조건부 통계량을 계산하기 위한 방법으로 크게 분할, 적용, 결합의 세 단계로 구성된다.

 

* DataFrame.gropuby

 - DataFrame을 분할 기준 컬럼을 기준으로 나누는 함수

 - 사용 구조: df.groupby(분할기준 칼럼)[적용 기준 칼럼].집계함수

// 사용구조가 상당히 중요하다. -> 기준으로 나누는 함수일 뿐이고, 구조를 통해서 데이터를 봐야 한다.

 - 주요 입력

  . by: 분할 기준 컬럼 (목록)

  . as_index : 분할 기준 컬럼들을 인덱스로 사용할 것인지 여부 (default: True)

// as _ index 하나의 새로운 컬럼으로 설정할 것인지, 분할 기준 컬럼들을 볼때.. replace 등을 쓸수도 있다. -> 상황에 맞게 사용하면 된다.

 - 여러 개의 집계 함수나 사용자 정의 함수를 쓰고 싶다면 agg 함수를 사용해야 한다.

 

* pivot_table 과 groupby 의 차이점

// 내용상으로는 차이가 없다.

// 하지만, 출력물에는 차이가 있다.

 - pivot_table 과 groupby 모두 조건부 통계량을 기준으로 데이터를 집계한다는 점에서 완전히 동일하다.

 - 하지만 출력물 구조의 차이가 있으므로, 상황에 맞는 함수 선택이 필요하다.

 - 보통은 출력 결과 자체가 결과물인 경우에는 pivot_table 을, 중간 산출물인 경우에는 groupby 를 사용한다.

 

* 실습

// 해석하는 것이 중요하다. 쇼핑몰 유형에 따른 수량의 평균이다라는 것을 생각하고 진행하면 된다.

// False 는 dataframe 으로 반환하고, True 일 경우에는 index 를 가지는 Series 형태로 return 된다.

 

// 간단하게 함수를 만들어서 사용할 수도 있다. agg 에 넣을 수 있다.

// multiindex 이다.

 

// pandas.DataFrame.groupby 의 documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True)

Parameters

bymapping, function, label, or list of labels

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an ndarray is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Split along rows (0) or columns (1).

levelint, level name, or sequence of such, default None

If the axis is a MultiIndex (hierarchical), group by a particular level or levels.

as_indexbool, default True

For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output.

sortbool, default True

Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.

group_keysbool, default True

When calling apply, add group keys to index to identify pieces.

squeezebool, default False

Reduce the dimensionality of the return type if possible, otherwise return a consistent type.

Deprecated since version 1.1.0.

observedbool, default False

This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers.

New in version 0.23.0.

dropnabool, default True

If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups

New in version 1.1.0.

 

// groupby 의 parameter 또한 다양하게 존재한다. dropna 의 경우에도 자주 사용하는 것 중에 하나이다.

 


 

[01. Part 1) 데이터 핸들링 Chapter 05. 보고 싶은 데이터 찾아보기 - 데이터 정렬과 인덱싱 - 01. 데이터 정렬]

 

* 리스트 및 튜플 정렬

 - sort: 리스트 및 튜플 자체를 정렬 (return 값이 없음)

  . reverse : 내림차순으로 정렬할 것인지 여부를 결정하는 매개 변수

  . Pandas 에서 inplace = True 로 설정한 것과 같다고 볼 수 있다.

 

 - sorted: 정렬된 리스트 및 튜플을 반환

  . reverse : 내림차순으로 정렬할 것인지 여부를 결정하는 매개 변수

  . key : 정렬 기준 함수 (주로 lambda 함수를 사용)

// lambda 는 길이가 길지 않기 때문에 lambda 를 사용한다.

 

* 실습

// L.sort( ) 한다고 해서 출력이 안된다.

// L 을 별도로 찍어줘야 한다.

 

// lambda 를 이용해서 어떤 요소를 기준으로 정렬할 수가 있다.

// lambda 를 abs(절대값) 을 기준으로 정렬하는 것이다. 3에 가까울수록 앞쪽으로 정렬된다.

// reverse = True 을 줘서 길이를 기준으로 내림차순 정렬하는 것이다.

 

* Series 정렬

 - sort_values 를 사용하면 Series를 손쉽게 정렬할 수 있다.

 - 주요 입력

  . ascending: 오름차순으로 정렬할 것인지 여부

// True: 오름 차순, False: 내림 차순

  . key : 정렬 기준 함수 (주로 lambda 함수를 사용)

  . na_position -> 결측이 있는 경우 어디에 배치할 것인지 결정 {first, last}

 

* 실습

// default 값들은 ascending = True 내림차순, key = None, na_postion = last

// na_position = last 라는 것은 결측들은 맨 뒤로 가게 된다.

// na_postion = first 로 바꾸면 결측들이 위에서 부터 나오게 된다.

 

* Series 요약 함수

 - value_counts : Series의 구성 요소의 빈도를 순서대로 출력하는 것이다.

  . ascending : 오름차순으로 정렬할 것인지 여부

  . normalize: 빈도 대시 비율을 출력할 것인지 여부

 - unique : Seried에 포함된 유니크한 값을 출력

  . 출력 결과의 데이터 타입: ndarray

  . 범주형 변수와 연속형 변수를 판단하는데 사용 가능하다.

// set 함수와 굉장히 유사하게 작동된다.

// unique 에는 데이터가 많다면 연속형, 적으면 범주형이라고 볼 수 있다.

 

* 실습

// index 는 value 이고, 뒤에는 count를 나타내는 것이다.

// value_count( ) 는 범주형 데이터에서 쓰는 것이 더 좋다.

 

// value count 를 더하고 전체를 나눠서.. normalize

// value_count 에서는 결측치가 포함이 안되는데, unique에서는 NaN 이 포함된다.

// len -> 로 작으면 범주형.. 많으면 연속형이라고 이해하면 된다.

 

// pandas.Series.value_counts 에 대한 Dcoumnetation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html

Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)

Parameters

normalizebool, default False

If True then the object returned will contain the relative frequencies of the unique values.

sortbool, default True

Sort by frequencies.

ascendingbool, default False

Sort in ascending order.

binsint, optional

Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data.

dropnabool, default True

Don’t include counts of NaN.

 

 

* DataFrame 정렬

 - sort_values 를 사용하면 DataFrame도 손쉽게 정렬할 수 있다.

 - 주요입력

  . by  : 정렬 기준 컬럼 (목록)

// DataFrame은 여러개의 데이터가 모여있기 때문에 by로 정해줘야 한다.

  . ascending : 오름차순으로 정렬할 것인지 여부

  . key: 정렬 기준 함수 (주로 lambda 함수를 사용)

  . na_position : 결측이 있는 경우 어디에 배치할 것인지 결정 {first, last}

 

 

* 실습

// by = 'A' 를 기준으로 정렬한다는 것이다... A가 작은순서대로 정렬이 된다.

// [c b] C를 먼저 기준으로 정렬하고 난뒤에 B를 기준으로 정렬한다.

 

// pandas.DataFrame.sort_values 에 대한 Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html

DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)

Parameters

bystr or list of str

Name or list of names to sort by.

  • if axis is 0 or ‘index’ then by may contain index levels and/or column labels.

  • if axis is 1 or ‘columns’ then by may contain column levels and/or index labels.

Changed in version 0.23.0: Allow specifying index or column level names.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Axis to be sorted.

ascendingbool or list of bool, default True

Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.

inplacebool, default False

If True, perform operation in-place.

kind{‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’

Choice of sorting algorithm. See also ndarray.np.sort for more information. mergesort is the only stable algorithm. For DataFrames, this option is only applied when sorting on a single column or label.

na_position{‘first’, ‘last’}, default ‘last’

Puts NaNs at the beginning if first; last puts NaNs at the end.

ignore_indexbool, default False

If True, the resulting axis will be labeled 0, 1, …, n - 1.

New in version 1.0.0.

keycallable, optional

Apply the key function to the values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect a Series and return a Series with the same shape as the input. It will be applied to each column in by independently.

New in version 1.1.0.

 

 

* DataFrame 중복 제거

 - drop_duplicates 함수를 사용하면 중복이 있는 행을 제거할 수 있다.

 - 주요 입력

  . subset: 중복 기준을 판단하는 컬럼 (목록)

  . keep: 중복이 있는 어느 부분을 남길 것인지 결정 {'first', 'last', 'false'}

  .. first : 첫 번째 행을 남김

  .. last : 마지막 행을 남김

  .. false : 중복 행을 모두 제거

 

* 실습

// A를 기준으로 중복된 값 제거 A를 기준으로 unique 한 값에 따라서 남는다. Default 가 first 이므로 첫행이 살아 있는 것이다.

 

// pandas.DataFrame.drop_duplicates 의 documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html

DataFrame.drop_duplicates(subset=None, keep='first', inplace=False, ignore_index=False)

Parameters

subsetcolumn label or sequence of labels, optional

Only consider certain columns for identifying duplicates, by default use all of the columns.

keep{‘first’, ‘last’, False}, default ‘first’

Determines which duplicates (if any) to keep. - first : Drop duplicates except for the first occurrence. - last : Drop duplicates except for the last occurrence. - False : Drop all duplicates.

inplacebool, default False

Whether to drop duplicates in place or to return a copy.

ignore_indexbool, default False

If True, the resulting axis will be labeled 0, 1, …, n - 1.

New in version 1.0.0.

 

// Sorting HOW TO 의 Documentation

docs.python.org/3/howto/sorting.html

 

 

[01. Part 1) 데이터 핸들링 Chapter 05. 보고 싶은 데이터 찾아보기 - 데이터 정렬과 인덱싱 - 02. 인덱서를 활용한 인덱싱]

// 데이터 시리즈를 할때 한번 했었지만 다시 리마인드 한다는 생각으로, 하지만, 중요한 내용이기때문에. 다시 한번 상기

 

* 인덱싱과 슬라이싱 (remind)

 - 판다스의 객체는 암묵적인 인덱스(위치 인덱스)와 명시적인 인덱스라는 두 종류의 인덱스가 있어, 명시적인 인덱스를 참조하는 loc 인덱서와 암묵적인 인덱스를 참조하는 iloc 인덱서가 존재한다.

// 암묵적..인덱스는 사용자가 설정한 것이 아니고, 명시적 인덱스는 사용자가 직접 설정한 것이라고 이해하면 된다.

 

// 데이터프레임일때는 리스트나 컬럼으로 접근

 

* 값 변경하기 (remind)

 - 인덱서를 사용하여 조회한 값을 직접 변경할 수 있다.

// 판다스에 있는 자료를 바꿀 때는 반드시 인덱서를 사용해야 한다.

// 이 외에도 방법은 있지만, 반드시 사용해야 한다고 기억해야 한다.

// loc[c, col2] 으로도 동일한 기대값을 가질 수 있다.

 

* 인덱서를 사용해야 하는 이유

 - DataFrame의 값을 바꾸는 경우에는 가장 자주 흔히 보는 경고로 SettingWithCopyWarning이 있다.

// warning 은 많이 보아왔다.

 - df['A'] 는 view를 반환하고, df.loc['A'] 는 copy된 값을 반환한다.

// loc[a] 에 저장하면 df 자체가 바뀔 수 없고, 값을 바꾸게 되면 df 자체가 바뀐다.

  . view 를 반환한 결과를 바꾸는 경우에는 원본 자체도 변경이 일어날 수 있다.

  . copy를 반환한 결과를 바꾸더라도 원본에는 변경이 없다.

 - 따라서 view를 반환하지 않도록 가능하면 인덱서를 사용해야만, 사용자의 의도대로 DataFrame을 변경할 수 있다.

 


 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
groupb_by 함수의 경우에는 데이터 처리에 있어서 굉장히 많이 사용하는 것을 보아왔다. 어떤식으로 묶어서 보는냐에 따라서 다양한 insight 가 나오게 된다. 그래서 더욱더 어렵다. 그 모든것의 판단은..역시 경험? 하.. 어렵구만...

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트