티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Normalize columns of a dataframe
데이터프레임의 열 정규화
문제 내용
I have a dataframe in pandas where each column has different value range. For example:
판다스 데이터프레임의 각 열(column)마다 값의 범위가 다르게 존재합니다. 예를 들어:
df:
데이터프레임:
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
Any idea how I can normalize the columns of this dataframe where each value is between 0 and 1?
각 값을 0에서 1사이의 범위에 위치하도록 데이터프레임의 열(column)을 정규화하려면 어떻게 해야 할까요?
My desired output is:
원하는 출력 결과는 다음과 같습니다:
A B C
1 1 1
0.765 0.5 0.7
0.8 0.7 0.18(which is 0.09/0.5)
높은 점수를 받은 Solution
one easy way by using Pandas: (here I want to use mean normalization)
판다스(Pandas)를 사용하면 쉽게 정규화할 수 있습니다. (평균 정규화를 사용하고 싶습니다.)
normalized_df=(df-df.mean())/df.std()
to use min-max normalization:
최소-최대 정규화를 사용하려면:
normalized_df=(df-df.min())/(df.max()-df.min())
Edit: To address some concerns, need to say that Pandas automatically applies colomn-wise function in the code above.
수정: 몇 가지 우려 사항을 다루기 위해 언급하자면, 위의 코드에서 판다스가 자동으로 열별 함수를 적용한다는 것입니다.
가장 최근 달린 Solution
Normalize
정규화
You can use minmax_scale
to transform each column to a scale from 0-1.
minmax_scale을 사용하여 각 열을 0-1 스케일로 변환할 수 있습니다.
from sklearn.preprocessing import minmax_scale
df[:] = minmax_scale(df)
Standardize
표준화
You can use scale
to center each column to the mean and scale to unit variance.
scale을 사용하여 각 열을 평균으로 중심을 맞추고 단위 분산으로 스케일할 수 있습니다.
from sklearn.preprocessing import scale
df[:] = scale(df)
Column Subsets
열 서브셋
Normalize single column
단일 열을 정규화
from sklearn.preprocessing import minmax_scale
df['a'] = minmax_scale(df['a'])
Normalize only numerical columns
숫자 열만 정규화
import numpy as np
from sklearn.preprocessing import minmax_scale
cols = df.select_dtypes(np.number).columns
df[cols] = minmax_scale(df[cols])
Full Example
전체 예제
# Prep
import pandas as pd
import numpy as np
from sklearn.preprocessing import minmax_scale
# Sample data
df = pd.DataFrame({'a':[0,1,2], 'b':[-10,-30,-50], 'c':['x', 'y', 'z']})
# MinMax normalize all numeric columns
cols = df.select_dtypes(np.number).columns
df[cols] = minmax_scale(df[cols])
# Result
print(df)
# a b c
# 0 0.0 1.0 x
# 2 0.5 0.5 y
# 3 1.0 0.0 z
Notes:
참고:
In all examples scale
can be used instead of minmax_scale
. Keeps index, column names or non-numerical variables unchanged. Function is applied for each column.
모든 예제에서 scale 대신 minmax_scale을 사용할 수 있습니다. 인덱스, 열 이름 또는 숫자가 아닌 변수는 변경되지 않습니다. 함수는 각 열에 대해 적용됩니다.
Caution:
주의:
For machine learning, use minmax_scale
or scale
after train_test_split
to avoid data leakage.
데이터 누수(data leakage)를 방지하려면 train_test_split 후 minmax_scale 또는 scale을 사용해야 합니다.
Info
정보
More info on standardization and normalization:
표준화(Standardization)와 정규화(Normalization)에 대한 자세한 내용은 다음을 참조하세요:
- https://machinelearningmastery.com/standardscaler-and-minmaxscaler-transforms-in-python/
- https://en.wikipedia.org/wiki/Normalization_(statistics)
- https://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing
출처 : https://stackoverflow.com/questions/26414913/normalize-columns-of-a-dataframe
'개발 > 파이썬' 카테고리의 다른 글
상위 디렉토리에서 파일을 가져오는 방법 (0) | 2023.03.06 |
---|---|
Python에서 CSV 데이터 한 줄(line) 읽는 방법 (0) | 2023.03.06 |
파이썬 딕셔너리 저장하기 (0) | 2023.03.03 |
맥에서 pip 루트 권한 실행시 "Permission Denied" 오류 발생 (0) | 2023.03.03 |
고유한 파일 이름 생성하기 (0) | 2023.03.03 |