본문 바로가기

데이터 분석 학습

16장 데이터를 추출하는 다양한 방법 (1)

반응형

16-1 [ ] 이용하기

조건을 충족하는 행 추출하기

import pandas as pd
df_raw = pd.read_csv('exam.csv')
df = df_raw.head(10)
df

# nclass 추출
df['nclass'] 

"""
0    1
1    1
2    1
3    1
4    2
5    2
6    2
7    2
8    3
9    3
Name: nclass, dtype: int64
"""
# nclass가 1인지 확인
df['nclass'] == 1

"""
0     True
1     True
2     True
3     True
4    False
5    False
6    False
7    False
8    False
9    False
Name: nclass, dtype: bool
"""
# nclass가 1이면 추출
df[df['nclass'] == 1]

# 수학 점수가 80점 이상이면 추출
df[df['math'] >= 80]

# nclass가 1이면서 수학 점수가 50점 이상
df[(df['nclass'] == 1) & (df['math'] >= 50)]

# 수학 점수가 50점 미만이거나 영어 점수가 50점 미만
df[(df['math'] < 50) | (df['english'] < 50)]

열 추출하기

df['id']

"""
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9    10
Name: id, dtype: int64
"""
df['nclass']

"""
0    1
1    1
2    1
3    1
4    2
5    2
6    2
7    2
8    3
9    3
Name: nclass, dtype: int64
"""
df[['id', 'nclass']]

열이 1개일 때 데이터 프레임 자료 구조 유지하기

# 시리즈로 추출
df['id']

"""
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9    10
Name: id, dtype: int64
"""
# 데이터 프레임으로 추출
df[['id']]

.을 이용해 변수를 간단하게 추출하기

# []를 이용해 변수 추출
df['math']  

"""
0    50
1    60
2    45
3    30
4    25
5    50
6    80
7    90
8    20
9    50
Name: math, dtype: int64
"""
# .을 이용해 변수 추출
df.math

"""
0    50
1    60
2    45
3    30
4    25
5    50
6    80
7    90
8    20
9    50
Name: math, dtype: int64
"""
df['math'].mean()

##출력: 50.0
df.math.mean()

##출력: 50.0

조건을 충족하는 행에서 열 추출하기

# nclass가 1인 행의 math 열
df[df['nclass'] == 1]['math']

"""
0    50
1    60
2    45
3    30
Name: math, dtype: int64
"""
# nclass가 1인 행의 math, english 열
df[df['nclass'] == 1][['math', 'english']]

 

[ ]를 pandas 함수와 함께 사용하기

# pandas 함수만 사용
df.groupby('nclass') \
  .agg(math    = ('math', 'mean'), 
       english = ('english', 'mean'))

# pandas 함수와 [] 함께 사용
df.groupby('nclass')[['math', 'english']].mean()

 

 

 

 

 

※ 해당 내용은 <Do it! 파이썬 데이터 분석>의 내용을 토대로 학습하며 정리한 내용입니다.

반응형