3. Subset Observations(Columns) (열 데이터 다루기)
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))
In [2]:
import pandas as pd
import seaborn as sns
In [3]:
# 예시 데이터 불러오기
df = sns.load_dataset('iris')
print(df.shape)
df.head()
(150, 5)
Out[3]:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa

데이터프레임에서 특정 컬럼 정보만 불러오기

In [4]:
columns = ['sepal_length', 'sepal_width', 'species']
df[columns].head()
Out[4]:
sepal_length sepal_width species
0 5.1 3.5 setosa
1 4.9 3.0 setosa
2 4.7 3.2 setosa
3 4.6 3.1 setosa
4 5.0 3.6 setosa
In [5]:
# 이 방식에서는 한글이나 특수문자가 들어간 컬럼명을 쓸 수 없음
df.sepal_width.head() 
Out[5]:
0    3.5
1    3.0
2    3.2
3    3.1
4    3.6
Name: sepal_width, dtype: float64
In [6]:
df['sepal_width'].head()
Out[6]:
0    3.5
1    3.0
2    3.2
3    3.1
4    3.6
Name: sepal_width, dtype: float64

정규 표현식으로 특정컬럼 불러오기

df.filter( regex = 'regex' )

  • '\.' : 점( . )을 포함하고 있는 문자열
In [7]:
df.filter(regex='\,').head(3)
Out[7]:
0
1
2
  • 'length$' : 특정문자열(length)로 끝나는 문자열
In [8]:
df.filter(regex='length$').head(3)
Out[8]:
sepal_length petal_length
0 5.1 1.4
1 4.9 1.4
2 4.7 1.3
  • '_' : _ 를 포함하고 있는 문자열
In [9]:
df.filter(regex='_').head(3)
Out[9]:
sepal_length sepal_width petal_length petal_width
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
  • '^sepal' : 특정문자열(Sepal)로 시작하는 문자열
In [10]:
df.filter(regex='^sepal').head(3)
Out[10]:
sepal_length sepal_width
0 5.1 3.5
1 4.9 3.0
2 4.7 3.2
  • *'^(?!species$).' : 특정문자열('species')이 없는 문자열
In [11]:
df.filter(regex='^(?!species).*').head(3)
Out[11]:
sepal_length sepal_width petal_length petal_width
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
  • '^x[1-5]$' : 특정문자(x)로 시작하고 특정문자(1, 2, 3, 4, 5)로 끝나는 문자열
In [12]:
df.filter(regex='^x[1-5]$').head(3)
Out[12]:
0
1
2

df.loc[ ]와 df.iloc[ ] 비교

In [13]:
df.loc[2:5, 'sepal_width':'petal_width']
Out[13]:
sepal_width petal_length petal_width
2 3.2 1.3 0.2
3 3.1 1.5 0.2
4 3.6 1.4 0.2
5 3.9 1.7 0.4

loc와는 다르게 iloc로 검색을 했을 때 a:b 면 b-1행까지 검색을 함
iloc는 인덱스번호만 입력이 가능함

In [14]:
df.iloc[2:5:,  1:3]
Out[14]:
sepal_width petal_length
2 3.2 1.3
3 3.1 1.5
4 3.6 1.4

loc 를 통해 logic 조건으로 행을 지정하고, 컬럼명을 선택할 수 있음

In [15]:
df.loc[df['sepal_length']>3 , ['sepal_length','sepal_width']].head()
Out[15]:
sepal_length sepal_width
0 5.1 3.5
1 4.9 3.0
2 4.7 3.2
3 4.6 3.1
4 5.0 3.6

+ Recent posts