본문 바로가기
스터디 열기

Pandas 연습 문제

문제 1

다음 코드의 출력 결과는 무엇일까요?

import pandas as pd
s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print(s.loc['b':'d'])
  1. b    2
    c    3
    d    4
    dtype: int64
    
  2. 2
    3
    4
    
  3. b    2
    c    3
    d    4
    e    5
    dtype: int64
    
  4. a    1
    b    2
    c    3
    d    4
    dtype: int64
    

문제 2

Series의 apply() 메서드를 사용할 때, 가장 효율적인 방법은 무엇인가요?

  1. 항상 lambda 함수 사용
  2. 가능한 NumPy 벡터화 연산 사용
  3. 항상 for 루프로 직접 구현
  4. Series를 리스트로 변환 후 리스트 컴프리헨션 사용

문제 3

s.map()과 s.apply()의 주요 차이점은 무엇인가요?

  1. map은 딕셔너리를 인자로 받을 수 있지만, apply는 불가능
  2. apply는 Series 전체에 대한 연산 가능, map은 개별 요소에만 적용
  3. map은 결측치를 자동으로 처리하지만, apply는 그렇지 않음
  4. apply는 반환값의 형태가 자유롭지만, map은 항상 Series 반환

문제 4

다음 코드의 출력 결과는 무엇인가요?

import pandas as pd
import numpy as np
s = pd.Series([1, 2, np.nan, 4, 5])
print(s.fillna(s.mean()))
  1. 0    1.0
    1    2.0
    2    3.0
    3    4.0
    4    5.0
    dtype: float64
    
  2. 0    1.0
    1    2.0
    2    3.5
    3    4.0
    4    5.0
    dtype: float64
    
  3. 0    1.0
    1    2.0
    2    3.0
    3    4.0
    4    5.0
    dtype: float64
    
  4. 0    1.0
    1    2.0
    2    NaN
    3    4.0
    4    5.0
    dtype: float64
    

문제 5

Series의 value_counts() 메서드 사용 시, 상대 빈도를 계산하려면 어떻게 해야 하나요?

  1. value_counts(normalize=True)
  2. value_counts(relative=True)
  3. value_counts(percentage=True)
  4. value_counts().div(len(s))

문제 6

Series의 결측치를 가장 효과적으로 처리하는 방법은 무엇인가요?

  1. 항상 dropna()로 모든 결측치 제거
  2. 항상 fillna()로 평균값 대체
  3. 항상 interpolate()로 보간
  4. 데이터의 특성과 분석 목적을 고려하여 적절한 방법 선택

문제 7

MultiIndex Series에서 특정 레벨의 인덱스만 선택하는 올바른 방법은 무엇인가요?

  1. s.index.get_level_values(level)
  2. s.select_level(level)
  3. s.index.levels[level]
  4. s.level_select(level)

문제 8

다음 코드의 출력 결과는 무엇인가요?

import pandas as pd
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([4, 5, 6], index=['b', 'c', 'd'])
print(pd.concat([s1, s2], axis=1))
  1.     0    1
    a  1.0  NaN
    b  2.0  4.0
    c  3.0  5.0
    d  NaN  6.0
    
  2.     0    1
    a    1  NaN
    b    2    4
    c    3    5
    d  NaN    6
    
  3. a  1
    b  2
    c  3
    b  4
    c  5
    d  6
    
  4. a  1    4
    b  2    5
    c  3    6
    

문제 9

Series의 astype() 메서드로 데이터 타입을 'category'로 변환하면 어떤 이점이 있나요?

  1. 메모리 사용량 감소
  2. 연산 속도 향상
  3. 결측치 자동 처리
  4. 1)과 2) 모두 해당

문제 10

다음 코드의 출력 결과는 무엇인가요?

import pandas as pd
s = pd.Series(['a', 'b', 'c', 'a', 'b', 'c', 'a'])
print(s.value_counts())
  1. a    3
    b    2
    c    2
    dtype: int64
    
  2. a    3
    b    2
    c    2
    
  3. a    0.428571
    b    0.285714
    c    0.285714
    dtype: float64
    
  4. a    3
    c    2
    b    2
    dtype: int64
    

문제 11

DataFrame에서 특정 열을 삭제하려면 어떤 메서드를 사용해야 하나요?

  1. remove()
  2. delete()
  3. drop()
  4. discard()

문제 12

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
result = df.T
print(result)
  1.    A  B
    0  1  4
    1  2  5
    2  3  6
    
  2.    0  1  2
    A  1  2  3
    B  4  5  6
    
  3.    0  1
    A  1  2
    B  4  5
    
  4.    A  B
    0  1  4
    1  2  5
    

문제 13

DataFrame에서 인덱스를 재설정하는 방법은 무엇인가요?

  1. reset_index()
  2. reindex()
  3. set_index()
  4. index_reset()

문제 14

DataFrame의 행을 합치는 방법으로 올바른 것은 무엇인가요?

  1. df.append()
  2. df.add()
  3. df.concat()
  4. df.combine()

문제 15

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
result = df.loc[:, 'A']
print(result)
  1. 0    1
    1    2
    2    3
    Name: A, dtype: int64
    
  2. A    1
    B    4
    Name: 0, dtype: int64
    
  3. A    1
    A    2
    A    3
    Name: A, dtype: int64
    
  4. 1    4
    2    5
    3    6
    Name: B, dtype: int64
    

문제 16

DataFrame에서 특정 행을 삭제하는 메서드는 무엇인가요?

  1. drop()
  2. remove()
  3. delete()
  4. discard()

문제 17

DataFrame의 특정 열을 기준으로 행의 순서를 변경하는 방법은 무엇인가요?

  1. df.sort()
  2. df.order()
  3. df.sort_index()
  4. df.sort_values()

문제 18

DataFrame에서 모든 결측치를 포함한 행을 삭제하려면 어떻게 해야 하나요?

  1. df.dropna(how='all')
  2. df.dropna(how='any')
  3. df.dropna(thresh=1)
  4. df.dropna(axis=1)

문제 19

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

import pandas as pd
df = pd.DataFrame({'A': [1, None, 3], 'B': [4, 5, None]})
result = df.fillna(0)
print(result)
  1.      A    B
    0  1.0  4.0
    1  0.0  5.0
    2  3.0  0.0
    
  2.      A  B
    0  1  4
    1  0  5
    2  3  0
    
  3.      A    B
    0  1.0  4.0
    1  2.0  5.0
    2  3.0  6.0
    
  4.      A    B
    0  1.0  4.0
    1  NaN  5.0
    2  3.0  NaN
    

문제 20

DataFrame에서 열의 데이터 타입을 변경하는 메서드는 무엇인가요?

  1. change_type()
  2. convert_type()
  3. astype()
  4. set_type()

문제 21

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

   import pandas as pd
   import numpy as np

   df = pd.DataFrame({'A': [1, 2, np.nan, 4], 'B': [5, np.nan, np.nan, 8], 'C': [9, 10, 11, 12]})
   result = df.dropna(thresh=2)
   print(result)
  1.       A    B     C
       0  1.0  5.0   9
       1  2.0  NaN  10
       3  4.0  8.0  12
    
  2.       A    B     C
       0  1.0  5.0   9
       3  4.0  8.0  12
    
  3.       A    B     C
       0  1.0  5.0   9
       1  2.0  NaN  10
       2  NaN  NaN  11
       3  4.0  8.0  12
    
  4.       A    B     C
       0  1.0  5.0   9
    

문제 22

fillna() 메서드를 사용할 때, 올바르지 않은 것은 무엇인가요?

  1. df.fillna(method='ffill') 는 이전 값으로 결측치를 채운다.
  2. df.fillna(method='bfill') 는 다음 값으로 결측치를 채운다.
  3. df.fillna(df.mean()) 는 각 열의 평균값으로 결측치를 채운다.
  4. df.fillna(axis=1) 는 각 행의 평균값으로 결측치를 채운다.

문제 23

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

df = pd.DataFrame({'A': ['1', '2', '3', '4'], 'B': [1.0, 2.0, 3.0, 4.0]})
df['A'] = df['A'].astype('int')
df['B'] = df['B'].astype('float32')
print(df.dtypes)
  1.    A    int32
       B    float32
       dtype: object
    
  2.    A    int64
       B    float32
       dtype: object
    
  3.    A    object
       B    float64
       dtype: object
    
  4.    A    int64
       B    float64
       dtype: object
    

문제 24

sort_values() 메서드를 사용할 때, 올바르지 않은 것은 무엇인가요?

  1. df.sort_values('column1', ascending=False) 는 'column1'을 기준으로 내림차순 정렬한다.
  2. df.sort_values(['column1', 'column2']) 는 'column1'을 먼저 정렬하고, 같은 값에 대해 'column2'로 정렬한다.
  3. df.sort_values('column1', inplace=True) 는 원본 DataFrame을 직접 수정한다.
  4. df.sort_values('column1', axis=1) 는 'column1'의 값을 기준으로 열을 정렬한다.

문제 25

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

df1 = pd.DataFrame({'key': ['A', 'B', 'C'], 'value': [1, 2, 3]})
df2 = pd.DataFrame({'key': ['A', 'B', 'D'], 'value': [4, 5, 6]})
result = pd.merge(df1, df2, on='key', how='outer', suffixes=('_left', '_right'))
print(result)
  1.      key  value_left  value_right
       0   A         1.0          4.0
       1   B         2.0          5.0
       2   C         3.0          NaN
       3   D         NaN          6.0
    
  2.      key  value_left  value_right
       0   A         1.0          4.0
       1   B         2.0          5.0
    
  3.      key  value
       0   A     1
       1   B     2
       2   C     3
       3   A     4
       4   B     5
       5   D     6
    
  4.      key  value_left  value_right
       0   A         1.0          4.0
       1   B         2.0          5.0
       2   C         3.0          NaN
    

문제 26

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

   import pandas as pd
   df = pd.DataFrame({'A': [1, np.nan, 3], 'B': [4, 5, np.nan]})
   result = df.interpolate()
   print(result)
  1.       A    B
       0  1.0  4.0
       1  2.0  5.0
       2  3.0  5.0
    
  2.       A    B
       0  1.0  4.0
       1  NaN  5.0
       2  3.0  NaN
    
  3.       A    B
       0  1.0  4.0
       1  1.0  5.0
       2  3.0  5.0
    
  4.       A    B
    
    
       0  1.0  4.0
       1  2.0  5.0
       2  3.0  NaN
    

문제 27

DataFrame에서 특정 열을 기준으로 그룹화하고 여러 집계 함수를 적용하려면 어떻게 해야 하나요?

  1. df.groupby('column').apply(['mean', 'sum'])
  2. df.groupby('column').agg({'A': 'mean', 'B': 'sum'})
  3. df.groupby('column').transform(['mean', 'sum'])
  4. df.groupby('column').aggregate(['mean', 'sum'])

문제 28

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

import pandas as pd
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar'],
                   'B': ['one', 'one', 'two', 'two'],
                   'C': [1, 2, 3, 4]})
result = df.pivot(index='A', columns='B', values='C')
print(result)
  1.     B  one  two
       A
       bar  2  4
       foo  1  3
    
  2.     B  one  two
       A
       bar  1  3
       foo  2  4
    
  3.     one  two
       A
       bar  1  3
       foo  2  4
    
  4.     one  two
       A
       bar  2  4
       foo  1  3
    

문제 29

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

import pandas as pd
import numpy as np

df = pd.DataFrame({
      'A': [1, 2, 3, 4],
      'B': [np.nan, 2, np.nan, 4],
      'C': [5, np.nan, np.nan, 8]
})

result = df.fillna(df.mean())
print(result)
  1.       A    B    C
       0  1.0  3.0  5.0
       1  2.0  2.0  6.5
       2  3.0  3.0  6.5
       3  4.0  4.0  8.0
    
  2.       A    B    C
       0  1.0  3.0  5.0
       1  2.0  2.0  6.5
       2  3.0  2.0  6.5
       3  4.0  4.0  8.0
    
  3.       A    B    C
       0  1.0  NaN  5.0
       1  2.0  2.0  NaN
       2  3.0  NaN  NaN
       3  4.0  4.0  8.0
    
  4.       A    B    C
       0  1.0  NaN  5.0
       1  2.0  2.0  6.5
       2  3.0  NaN  6.5
       3  4.0  4.0  8.0
    

문제 30

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

import pandas as pd

df = pd.DataFrame({
   'A': ['foo', 'bar', 'foo', 'bar'],
   'B': ['one', 'one', 'two', 'two'],
   'C': [1, 3, 2, 4]
})

result = df.pivot_table(index='A', columns='B', values='C', aggfunc='sum')
print(result)
  1.    B  one  two
      A
      bar  3  4
      foo  1  2
    
  2.    B  one  two
      A
      bar  4  3
      foo  2  1
    
  3.    B  one  two
      A
      bar  3  4
      foo  2  1
    
  4.    B  one  two
      A
      bar  4  2
      foo  1  3
    

문제 31

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 11, 12]})
df.iloc[1, 1] = np.nan
result = df.fillna(method='ffill').fillna(method='bfill') - df
print(result.iloc[1:3, 1:])
  1.       B    C
       1  0.0  0.0
       2  1.0  0.0
    
  2.       B    C
       1  1.0  0.0
       2  0.0  0.0
    
  3.       B    C
       1  NaN  0.0
       2  0.0  0.0
    
  4.       B    C
       1  -1.0  0.0
       2  0.0  0.0
    

문제 32

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

df = pd.DataFrame({'A': ['a', 'b', 'a', 'b'], 'B': [1, 2, 3, 4], 'C': [5, 6, 7, 8]})
result = df.groupby('A').agg({'B': 'first', 'C': 'last'}).reset_index()
print(result.loc[result['B'] < result['C'], 'A'].iloc[0])
  1. 'a'
  2. 'b'
  3. IndexError
  4. None of the above

문제 33

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'C': [7, 8]})
result = pd.concat([df1, df2], axis=0).fillna(0).astype(int)
print(result.iloc[2:, 1:].sum().sum())
  1. 7
  2. 8
  3. 15
  4. 19

문제 34

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

df = pd.DataFrame({'A': ['X', 'Y', 'Z', 'X', 'Y'], 'B': [1, 2, 3, 4, 5]})
result = df.set_index('A').loc[['X', 'Y', 'Z', 'W'], 'B'].reset_index()
print(result['B'].fillna(method='ffill').sum())
  1. 15
  2. 12
  3. 18
  4. ValueError

문제 35

다음 코드의 실행 결과로 올바른 것은 무엇인가요?

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
mask = df > df.mean()
result = df[mask].fillna(0).astype(int)
print(result.iloc[:2, 1:].values.flatten().tolist())
  1. [5, 6, 8, 9]
  2. [0, 6, 0, 9]
  3. [5, 0, 8, 0]
  4. [0, 0, 8, 9]

정답

문제 번호정답문제 번호정답문제 번호정답문제 번호정답
11113211313
22122224321
31131232333
41143*24434없음*
5115125135없음*
64161261
71174274
81181281
94191291
101203301

정답 풀이와 바로잡기 (pandas 3.0 기준으로 모든 코드 문제를 실제로 실행해 확인했습니다. 이 교재 화면의 실행 블록도 pandas 3.0입니다.)

  • 문제 4: 결측치를 뺀 평균은 (1 + 2 + 4 + 5) / 4 = 3.0이므로 정답은 1번입니다(3번 보기도 1번과 같은 내용). 이전 정답표의 2번(3.5)은 잘못입니다.
  • 문제 10: pandas 2.0부터 value_counts() 결과 맨 아래에 Name: count, dtype: int64가 함께 나옵니다. 값이 맞는 1번을 정답으로 봅니다.
  • 문제 14: df.append()는 pandas 2.0에서 없어졌습니다. 행을 합치는 올바른 방법은 pd.concat([df1, df2])입니다. 3번은 df.concat()으로 적혀 있지만 concat은 데이터프레임의 메서드가 아니라 pd.concat() 함수이므로, 보기 중 정확히 맞는 것은 없습니다. pd.concat을 뜻하는 3번을 정답으로 봅니다.
  • 문제 21: thresh=2는 '값이 있는 칸이 2개 이상인 행만 남긴다'는 뜻입니다. 1번 행(2.0, NaN, 10)은 값이 2개라 남으므로 정답은 1번입니다. 2번 행(NaN, NaN, 11)만 빠집니다.
  • 문제 22, 31: fillna(method='ffill'), fillna(method='bfill')은 pandas 2.1부터 권장하지 않고 pandas 3.0에서 없어져 이제 TypeError가 납니다. 같은 일은 df.ffill(), df.bfill()로 합니다. 문제 22의 정답(4번)은 그대로입니다.
  • 문제 28: pivot() 결과는 열 이름 줄에 B가 함께 표시되는 1번입니다. 4번도 값은 같지만 출력 모양은 1번이 맞습니다.
  • 문제 31: df의 [1, 1] 칸이 NaN이므로 채운 값 - NaN도 NaN입니다. 정답은 3번입니다. 이전 정답표의 2번은 잘못입니다.
  • 문제 33: 위아래로 합친 뒤 3·4번째 행(iloc 2:)의 B, C 열은 (0, 7), (0, 8)이라 합은 15, 정답은 3번입니다.
  • 문제 34: 인덱스에 없는 'W'를 loc에 리스트로 넣으면 pandas 1.0부터 KeyError가 납니다. 보기에 KeyError가 없어 정답이 없습니다. 없는 이름을 NaN으로 채우며 가져오려면 loc 대신 reindex(['X', 'Y', 'Z', 'W'])를 씁니다.
  • 문제 35: df.mean()은 열마다 평균(A 2, B 5, C 8)을 냅니다. 처음 두 행의 B, C 값(4, 7, 5, 8)은 모두 평균보다 크지 않아 0이 되므로 결과는 [0, 0, 0, 0]이고, 보기 중 정답이 없습니다.
import pandas as pd
import numpy as np

# 문제 31: fillna(method=...) 대신 ffill()/bfill()
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 11, 12]}).astype(float)
df.iloc[1, 1] = np.nan
print((df.ffill().bfill() - df).iloc[1:3, 1:])

# 문제 35: 열 평균과 비교
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
print(df.mean().tolist())
print(df[df > df.mean()].fillna(0).astype(int).iloc[:2, 1:].values.flatten().tolist())

마지막 수정