데이터 프레임에서 값을 조회하는 방법중 loc와 iloc 방법을 소개합니다.

loc는 행이나 열의 라벨을 직접 조회가능하며, iloc는 숫자의 형태로 접근 가능합니다.

 

우선 실습으로 사용할 데이터프레임을 제작합니다.

import pandas as pd
my_dictionary2 = {"col1":[0,1,2,3], "col2": pd.Series([1,2,3,4],
						index=["A","B","C","D"]),"col3":['A','B','C','D']}
df=pd.DataFrame(data=my_dictionary2,index=["A","B","C","D"])
df

우선 loc를 이용하여 행을 탐색합니다.

df.loc["A"]

두가지 이상의 행을 탐색하고 싶은 경우에는 다음과 같습니다.

df.loc[["A","B"]]

슬라이싱도 사용가능합니다.

df.loc["A":"C"]

 

열을 탐색하고 싶은 경우에는 조금 다르게 사용해야합니다.

만약 위의 방법 그대로 적용하는경우 다음과 같이 오류가 발생합니다.

df.loc["col1"]

다음과 같은 방법을 사용합니다.

df.loc[:,"col1"]

그외에 이러한 방법도 가능합니다.

df.loc[:]["col1"]

 

마지막으로 특정행의 특정 열의 값을 찾고싶다면 다음과 같이 수행합니다.

df.loc["A"]["col1"]


iloc의 경우 행이나 열의 라벨을 이용해 접근하는것이 아닌 숫자의 형태로 접근 가능합니다.

배열을 생각하시면 편합니다.

 

우선 행을 접근합니다.

df.iloc[1]

배열은 시작이 0이기에 1 행을 접근한 경우 두번째 행이 출력된 것을 알 수 있습니다.

 

마찬가지로 열에 대한 접근은 다음과 같습니다.

df.iloc[:,1]

마지막으로 행과 열 모두 지정해서 접근합니다.

df.iloc[0,0]

 

참고

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html

 

pandas.DataFrame.loc — pandas 1.4.3 documentation

A slice object with labels, e.g. 'a':'f'. Warning Note that contrary to usual python slices, both the start and the stop are included

pandas.pydata.org

 

'Others > Data Science' 카테고리의 다른 글

Preprocessing (3) Encoding  (0) 2022.07.18
Preprocessing (2) 누락된 값의 처리(Null)  (0) 2022.07.15
Pandas - DataFrame (2) 삭제  (0) 2022.07.14
Preprocessing (1) train_test_split  (0) 2022.07.14
Pandas - DataFrame (1) 생성  (0) 2022.07.14

우선 데이터프레임을 생성합니다.

my_dictionary = {"col1":[0,1,2,3], "col2": pd.Series([1,2,3],index=[1,2,3])}
df=pd.DataFrame(data=my_dictionary, index=[0,1,2,3])
df

Drop 명령어를 사용해서 행,열을 제거 가능합니다.

 

1. 행 제거

df.drop([0])

또는 index를 직접 지정하는것도 가능합니다.

df.drop(index=0)

2. 열제거

두가지 방법이 존재합니다. axis=1을 설정하는 방법과 columns=[] 를 사용하는 방법이 있습니다.

df.drop(['col1'],axis=1)
df.drop(columns = ['col1'])

결과는 동일합니다.

 

3. Inplace

inplace를 사용하지 않는경우 실제데이터에 drop한 결과가 반영되지 않습니다.

사용하지 않은경우 (inplace = False)

df.drop(['col1'],axis=1)
df

 

사용한 경우 (inplace =True)

df.drop(['col1'],axis=1,inplace=True)
df

 

※참고

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html

 

pandas.DataFrame.drop — pandas 1.4.3 documentation

next pandas.DataFrame.drop_duplicates

pandas.pydata.org

 

※실습에서 사용된 데이터는 Iris data set입니다.

 

데이터를 학습과 테스트하기위해 분할하는 과정을 수행한다.

'Scikit Learn'의 train_test_split 함수를 이용하여 분할하는 방법을 소개한다.

 

우선 scikit learn의 train_test_split 함수를 불러온다.

from sklearn.model_selection import train_test_split

기본적인 사용방법은 아래와 같습니다.

x_train, x_test, y_train, y_test = train_test_split(x_data,y_data, test_size= 0.2, random_state=42)

위의 코드는 데이터 x,y를 train 80%, test 20%의 비율로 랜덤하게 분할한다는 것입니다.

 

그런데 해당코드로 분할하게 되는경우 특정 값이 과도하게 몰려 정확도가 낮아지는 경우가 발생합니다.

따라서 각 계층마다 적절한 수를 추출하는 계층적 샘플링이 이루어져야 합니다.

train_test_split에서는 stratify를 사용하게되면 됩니다.

x_train, x_test, y_train, y_test = train_test_split(x_data,y_data, 
					test_size= 0.2, random_state=42, stratify = y_data)

 

아래는 iris 데이터를 이용한 실습입니다.

 

1. stratify 미적용

x_train, x_test, y_train, y_test = train_test_split(df_features,df['target'], test_size= 0.3, random_state=42)
y_test.hist()

다음과 같이 테스트셋의 불균형이 나타납니다.

 

2. stratify 적용

x_train2, x_test2, y_train2, y_test2 = train_test_split(df_features,df['target'], test_size= 0.3, random_state=42,stratify = df['target'])
y_test2.hist()

테스트 값의 분포가 동일한 것을 확인 할 수 있습니다.

판다스는 데이터 프레임과 시리즈 두 분류로 나누어 진행합니다.

 

데이터프레임을 처음 보면 흔히 보게되는 표를 떠올립니다. 마찬가지로 행과 열이 존재하며, 2차원의 형태로 이루어져있습니다. 판다스를 이용하면 데이터프레임의 직접적인 조작이 가능해지고, 파일저장, 읽기등의 기능을 수행가능합니다.

 

판다스 패키지의 데이터프레임 클래스입니다. 구성은 다음과 같습니다.

  - class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)

 

Import.

우선 판다스를 불러옵니다.

import pandas as pd

 

데이터 프레임 생성방법.

 

1. 딕셔너리를 이용한 생성.

my_dictionary = {"col1":[1,2],"col2":[3,4],"col3":[5,6]}
df = pd.DataFrame(data=my_dictionary)
df

2. 시리즈를 이용하는 방법.

my_dictionary2 = {"col1":[0,1,2,3], "col2": pd.Series([1,2,3],index=[1,2,3])}
df2=pd.DataFrame(data=my_dictionary2, index=[0,1,2,3])
df2

※ 위의 방법의 경우 행은 4개이나, 시리즈 데이터는 3개이다. 데이터 프레임 생성시(2번째 줄) index를 설정하지 않으면 길이가 맞지 않아 정상적으로 생성되지 않는다.

my_dictionary2 = {"col1":[0,1,2,3], "col2": pd.Series([1,2,3],index=[1,2,3])}
df2=pd.DataFrame(data=my_dictionary2)
df2

3. numpy array를 사용하는 방법.

import numpy as np
df3 = pd.DataFrame(np.array([[1,2,3],[4,5,6],[7,8,9]]),columns=['col1','col2','col3'])
df3

※dtype을 이용하면 데이터의 타입도 지정 가능하다.

 

 

참고 - 해당 포스팅은 판다스의 데이터프레임 document를 참고하였습니다.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html#

 

pandas.DataFrame — pandas 1.4.3 documentation

Column labels to use for resulting frame when data does not have them, defaulting to RangeIndex(0, 1, 2, …, n). If data contains column labels, will perform column selection instead.

pandas.pydata.org

 

+ Recent posts