오늘은 어제까지 배웠던 내용 중 중요한 내용을 다시 정리한 뒤, 객체 복사에 대한 개념을 배웠다. 그 뒤 NumPy와 Pandas에 대해 공부했다.
append(x) : x를 리스트 마지막에 추가remove(x) : x를 삭제sort() : 오름차순 정렬, 자료형이 섞여 있으면 에러 발생items() : 딕셔너리의 모든 키와 값을 튜플로 묶어서 반환keys() : 딕셔너리의 모든 키를 반환values() : 딕셔너리의 모든 값을 반환값1 if 조건1 else 값2'합격' if scores[0] >= 90 else '재검사'
# else 뒤에 새로운 조건 사용 가능
'합격' if scores[0] >= 90 else '재검사' if scores[0] >= 80 else '불합격'
[i ** 2 for i in nums]
[i ** 2 for i in nums if i % 2 == 0]
[i ** 2 if i % 2 == 0 else i * 2 for i in nums]
() 로 사용하거나 변수에 할당하여 사용 가능(lambda hgt, wgt: wgt / (hgt / 100) ** 2)(175, 70)
bmi2 = lambda hgt, wgt: wgt / (hgt / 100) ** 2
bmi2(175, 70)
a = [[1, 2], [3, 4]]
b = a
print(id(a)) # 2758672173056
print(id(b)) # 2758672173056
print(id(a) == id(b)) # True
b[0] = 9
print(b) # [9, [3, 4]]
print(a) # [9, [3, 4]]
a = [[1, 2], [3, 4]]
b = a.copy()
print(id(a)) # 2758666124160
print(id(b)) # 2758672176640
print(id(a) == id(b)) # False
print(id(a[0])) # 2758672165568
print(id(b[0])) # 2758672165568
print(id(a[0]) == id(b[0])) # True
b[0] = 99
print(b) # [99, [3, 4]]
print(a) # [[9, 2], [3, 4]]
b[1][0] = 9
print(b) # [99, [9, 4]]
print(a) # [[9, 2], [9, 4]]
a = [[1, 2], [3, 4]]
b = a * 2
print(a) # [[1, 2], [3, 4]]
print(b) # [[1, 2], [3, 4], [1, 2], [3, 4]]
b[0][0] = 9
print(a) # [[9, 2], [3, 4]]
print(b) # [[9, 2], [3, 4], [9, 2], [3, 4]]
import copy : 파이썬 표준 라이브러리print(id(a)) # 2758672196096
print(id(b)) # 2758672180736
print(id(a) == id(b)) # False
print(id(a[0])) # 2758672775936
print(id(b[0])) # 2758672062464
print(id(a[0]) == id(b[0])) # False
b[0][0] = 9
print(b) # [[9, 2], [3, 4]]
print(a) # [[1, 2], [3, 4]]
array.ndim : 배열의 차원 반환array.shape : axis 축에 따른 원소 개수를 튜플로 반환array.size : 전체 원소 개수를 정수로 반환array.dtype : 원소의 자료형을 반환a = 1
ar0 = np.array(a)
a # 1
ar0 # array(1)
type(ar0) # numpy.ndarray
ar0.ndim # 0
ar0.shape # ()
ar0.size # 1
ar0.dtype # dtype('int64')
ar1 = np.array(li1)
ar1
# li1 = [1, 2, 3] # array([1, 2, 3])
# li1 = [1, 2.0, 3] # array([1., 2., 3.])
# li1 = [1, 2.0, '3'] # array(['1', '2.0', '3'], dtype='<U32')
type(ar1) # numpy.ndarray
ar1.ndim # 1
ar1.shape # (3,)
ar1.size # 3
ar1.dtype # dtype('<U32')
ar1.astype(int)
# ValueError: invalid literal for int() with base 10: np.str_('2.0')
ar1.astype(float).astype(int).astype(str).astype(int)
# array([1, 2, 3])
np.array(li1, dtype=int) # array([1, 2, 3])
np.array(li1, dtype=float) # array([1., 2., 3.])
np.array(li1, dtype=str) # array(['1', '2.0', '3'], dtype='<U3')
np.array(object=li1, dtype=object) # array([1, 2.0, '3'], dtype=object)
Pandas 시리즈를 생성할 때 원소에 문자열을 포함하면 시리즈의 원소 자료형을 object로 자동 변환
시리즈의 자료형이 object일 대 문자열과 수치형 원소가 섞여 있을 수 있음
np.arange() : 시작 이상 끝 미만의 정수 배열을 지정한 간격으로 생성np.arange(6) # array([0, 1, 2, 3, 4, 5])
np.arange(1, 6) # array([1, 2, 3, 4, 5])
np.arange(1, 6, 2) # array([1, 3, 5])
np.arange(0, 1, 0.1) # array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
np.arange(0, 1.1, 0.1) # array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
np.linspace() : 시작부터 끝까지 균일 간격으로 지정한 개수만큼 숫자를 생성 (float)np.linspace(0, 1, 10+1) # array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
np.tile(ar1, 2)
# array(['1', '2.0', '3', '1', '2.0', '3'], dtype='<U32')
np.repeat(ar1, 2)
# array(['1', '1', '2.0', '2.0', '3', '3'], dtype='<U32')
np.repeat(ar1, [3, 2, 1])
# array(['1', '1', '1', '2.0', '2.0', '3'], dtype='<U32')
ar1 = np.arange(1, 12, 2)
ar1 # array([ 1, 3, 5, 7, 9, 11])
ar1[0] # np.int64(1)
ar1[1] # np.int64(3)
ar1[-1] # np.int64(11)
ar1[0].item() # 1
type(ar1[0]) # numpy.int64
type(ar1[0].item()) # int
ar1[0:3] # array([1, 3, 5])
ar1[:3] # array([1, 3, 5])
ar1[3:] # array([ 7, 9, 11])
ar1[:] # array([ 1, 3, 5, 7, 9, 11])
ar1[[3, 1, 2]] # array([7, 3, 5])
ar1[[3, 3, 3]] # array([7, 7, 7])
ar1[[3, 1, 2, 0, 4, 5]] # array([ 7, 3, 5, 1, 9, 11])
ar1[[3, 1, 2, 0, 4, 5, 3, 1, 2, 0, 4, 5]]
# array([ 7, 3, 5, 1, 9, 11, 7, 3, 5, 1, 9, 11])
ar1[[False, False, False, True, True, True]] # array([ 7, 9, 11])
ar1[ar1 >= 7] # array([ 7, 9, 11])
li2 = [[1, 3, 5], [7, 9, 11]]
ar2 = np.array(li2)
ar2
# array([[ 1, 3, 5],
# [ 7, 9, 11]])
type(ar2) # numpy.ndarray
ar2.ndim # 2
ar2.shape # (2, 3)
ar2.size # 6
ar2.dtype # dtype('int64')
reshape() : 1차원 배열을 2차원 배열로 변환ar1.reshape(2, 3)
# array([[ 1, 3, 5],
# [ 7, 9, 11]])
# order 속성 변경
ar1.reshape(2, 3, order='F')
# array([[ 1, 5, 9],
# [ 3, 7, 11]])
ar2 = ar1.reshape(2, -1)
ar2
# array([[ 1, 3, 5],
# [ 7, 9, 11]])
ar2 = ar1.reshape(-1, 3)
ar2
# array([[ 1, 3, 5],
# [ 7, 9, 11]])
flatten() : 2차원 배열을 1차원 배열로 변환ravel()ar2.flatten()
# array([ 1, 3, 5, 7, 9, 11])
ar2.ravel()
# array([ 1, 3, 5, 7, 9, 11])
ar2
# array([[ 1, 3, 5],
# [ 7, 9, 11]])
ar2[0, 0] # np.int64(1)
ar2[0] # array([1, 3, 5])
ar2[:, 0] # array([1, 7])
ar2[0:2, 0:2]
# array([[1, 3],
# [7, 9]])
ar2[:, 1:3]
# array([[ 3, 5],
# [ 9, 11]])
ar2[:, [2, 1]]
# array([[ 5, 3],
# [11, 9]])
ar1 = np.array([[0, 1, 2]])
ar1 # array([[0, 1, 2]])
ar1 + 1 # array([[1, 2, 3]])
ar2 = ar1.reshape(-1, 1)
ar2
# array([[0],
# [1],
# [2]])
ar2 * 2
# array([[0],
# [2],
# [4]])
| 구분 | 상세 내용 | 구분 | 상세 내용 | 구분 | 상세 내용 |
|---|---|---|---|---|---|
np.e | 자연상수(2.718…) | np.sqrt() | 제곱근 | np.mean() | 평균 |
np.pi | 파이(3.14…) | np.power() | 거듭제곱 | np.median() | 중위수 |
np.nan | 결측값(float) | np.exp() | 자연상수 거듭제곱 | np.var() | 분산 |
np.inf | 무한대 | np.log() | 자연 로그 | np.std() | 표준편차 |
np.abs() | 절대값 | np.sum() | 모든 원소 덧셈 | np.min() | 최솟값 |
np.floor() | 소수점 버림 | np.cumsum() | 모든 원소 누적 덧셈 | np.max() | 최댓값 |
np.ceil() | 소수점 올림 | np.prod() | 모든 원소 곱셈 | np.argmin() | 최솟값의 인덱스 |
np.round() | 반올림 | np.dot() | 내적 계산 | np.argmax() | 최댓값의 인덱스 |
np.diff() | 원소 간 차이 | np.size() | 원소 개수 | np.argsort() | 오름차순 인덱스 |
ar1 = np.array([1, 4, 3, 5, 2, 4, 3, 5, 1])
np.min(ar1) # np.int64(1)
np.max(ar1) # np.int64(5)
# 값이 여러개 있을 대 첫 번째 인덱스만 반환
np.argmin(ar1) # np.int64(0)
np.argmax(ar1) # np.int64(3)
# 배열 원소를 오름차순 정렬하고 인덱스만 반환
np.argsort(ar1)
# array([0, 8, 4, 6, 2, 5, 1, 3, 7])
seed = 1
np.random.seed(seed)
np.random.rand()
for i in range(5):
np.random.seed(seed)
print(np.random.randint(0, 5, 1))
for i in range(10):
lotto = np.random.choice(range(1,46), 6, replace=False)
lotto = [i.item() for i in lotto]
print(sorted(lotto))
li1 = [1, 2, 3]
ar1 = np.array(li1)
ar1
# array([1, 2, 3])
sr = pd.Series(li1)
sr
# 0 1
# 1 2
# 2 3
# dtype: int64
li1 = [1, 2.0, 3]
ar1 = np.array(li1)
ar1
# array([1., 2., 3.])
sr = pd.Series(li1)
sr
# 0 1.0
# 1 2.0
# 2 3.0
# dtype: float64
li1 = [1, 2.0, '3']
ar1 = np.array(li1)
ar1
# array(['1', '2.0', '3'], dtype='<U32')
sr = pd.Series(li1)
sr
# 0 1
# 1 2.0
# 2 3
# dtype: object
type(sr) # pandas.core.series.Series
sr.ndim # 1
sr.shape # (3,)
sr.size # 3
sr.dtype # dtype('O')
for i in sr:
print(type(i))
# <class 'int'>
# <class 'float'>
# <class 'str'>
sr.astype(str) + '1'
# 0 11
# 1 2.01
# 2 31
# dtype: object
sr.astype(int) + 1
# 0 2
# 1 3
# 2 4
# dtype: int64
sr.astype(float) + 1
# 0 2.0
# 1 3.0
# 2 4.0
# dtype: float64
sr.astype(bool)
# 0 True
# 1 True
# 2 True
# dtype: bool
index : 인덱스 객체 확인sr.index # RangeIndex(start=0, stop=3, step=1)
pd.Series(li1, index=[1, 2, 3])
# 1 1
# 2 2.0
# 3 3
# dtype: object
pd.Series(li1, index=[1.0, 2.0, 3.0])
# 1.0 1
# 2.0 2.0
# 3.0 3
# dtype: object
pd.Series(li1, index=['a', 'b', 'c'])
# a 1
# b 2.0
# c 3
# dtype: object
pd.Series(li1, index=[1, 1, 1])
# 1 1
# 1 2.0
# 1 3
# dtype: object
sr.index = [1, 2, 3]
sr
# 1 1
# 2 2.0
# 3 3
# dtype: object
sr.index = [1.0, 2.0, 3.0]
sr
# 1.0 1
# 2.0 2.0
# 3.0 3
# dtype: object
sr.index = ['a', 'b', 'c']
sr
# a 1
# b 2.0
# c 3
# dtype: object
sr.index = [1, 1, 1]
sr
# 1 1
# 1 2.0
# 1 3
# dtype: object
di = {'a': 1, 'b': 2, 'c': 3}
sr = pd.Series(di)
sr
# a 1
# b 2
# c 3
# dtype: int64
sr
# a 1
# b 2
# c 3
# dtype: int64
sr[0]
# FutureWarning
# np.int64(1)
sr.iloc[0]
# np.int64(1)
sr['a']
# np.int64(1)
sr[0:3]
# a 1
# b 2
# c 3
# dtype: int64
sr['a':'c']
# a 1
# b 2
# c 3
# dtype: int64
sr[[0, 2]]
# a 1
# c 3
# dtype: int64
sr[[True, False, False]]
# a 1
# dtype: int64
sr[sr < 3]
# a 1
# b 2
# dtype: int64
sr.iloc[0]
# np.int64(1)
sr.iloc[0:3]
# a 1
# b 2
# c 3
# dtype: int64
sr.iloc[[0]]
# a 1
# dtype: int64
sr.iloc[[0, 2]]
# a 1
# c 3
# dtype: int64
# 불리언 인덱싱 지원 X
sr.iloc[sr < 3]
# ValueError: iLocation based boolean indexing cannot use an indexable as a mask
sr.loc['a']
# np.int64(1)
sr.loc['a':'c']
# a 1
# b 2
# c 3
# dtype: int64
sr.loc[['a']]
# a 1
# dtype: int64
sr.loc[['a', 'c']]
# a 1
# c 3
# dtype: int64
sr.loc[sr < 3]
# a 1
# b 2
# dtype: int64
sr
# a 1
# b 2
# c 3
# dtype: int64
sr.loc['d'] = 4
sr
# a 1
# b 2
# c 3
# d 4
# dtype: int64
sr.loc['d'] = 5
sr
# a 1
# b 2
# c 3
# d 5
# dtype: int64
sr = sr.drop(index='d')
sr
# a 1
# b 2
# c 3
# dtype: int64
sr >= 1
# a True
# b True
# c True
# dtype: bool
for i in sr:
print(i >= 1 and i < 3)
# True
# True
# False
sr >= 1 and sr < 3
# ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
(sr >= 1) & (sr < 3)
# a True
# b True
# c False
# dtype: bool
(sr >= 1) | (sr < 3)
# a True
# b True
# c True
# dtype: bool
(sr >= 1) ^ (sr < 3)
# a False
# b False
# c True
# dtype: bool
~((sr >= 1) & (sr < 3))
# a False
# b False
# c True
# dtype: bool
li2 = [[1, 2, 3], [4, 5.0, '6']]
# 넘파이 배열
np.array(li2)
# array([['1', '2', '3'],
# ['4', '5.0', '6']], dtype='<U32')
# 데이터프레임
df = pd.DataFrame(li2)
df
# 0 1 2
# 0 1 2.0 3
# 1 4 5.0 6
df.ndim # 2
df.shape # (2, 3)
df.index # RangeIndex(start=0, stop=2, step=1)
df.columns # RangeIndex(start=0, stop=3, step=1)
df.dtypes
# 0 int64
# 1 float64
# 2 object
# dtype: object
df.values
# array([[1, 2.0, 3],
# [4, 5.0, '6']], dtype=object)
df.info()
# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 2 entries, 0 to 1
# Data columns (total 3 columns):
# # Column Non-Null Count Dtype
# --- ------ -------------- -----
# 0 0 2 non-null int64
# 1 1 2 non-null float64
# 2 2 2 non-null object
# dtypes: float64(1), int64(1), object(1)
# memory usage: 180.0+ bytes
index 로 행이름 변경df.index = range(1, 3)
df
# 0 1 2
# 1 1 2.0 3
# 2 4 5.0 6
columns 로 열이름 변경df.columns = ['A', 'B', 'C']
df
# A B C
# 1 1 2.0 3
# 2 4 5.0 6
pd.DataFrame(li2, index=range(1,3), columns=['A', 'B', 'C'])
# A B C
# 1 1 2.0 3
# 2 4 5.0 6
df
# A B C
# 1 1 2.0 3
# 2 4 5.0 6
iloc 사용으로 행 제어df.iloc[0, :]
# A 1
# B 2.0
# C 3
# Name: 1, dtype: object
df.iloc[0:2, :]
# A B C
# 1 1 2.0 3
# 2 4 5.0 6
df.iloc[[1, 0], :]
# A B C
# 2 4 5.0 6
# 1 1 2.0 3
iloc 사용으로 열 제어df.iloc[:, 0]
# 1 1
# 2 4
# Name: A, dtype: int64
df.iloc[:, 0:2]
# A B
# 1 1 2.0
# 2 4 5.0
df.iloc[:, [1, 0]]
# B A
# 1 2.0 1
# 2 5.0 4
loc 사용으로 행 제어df.loc[1, :]
# A 1
# B 2.0
# C 3
# Name: 1, dtype: object
df.loc[1:2, :]
# A B C
# 1 1 2.0 3
# 2 4 5.0 6
df.loc[[2, 1], :]
# A B C
# 2 4 5.0 6
# 1 1 2.0 3
loc 사용으로 열 제어df.loc[:, 'A']
# 1 1
# 2 4
# Name: A, dtype: int64
df.loc[:, 'A':'B']
# A B
# 1 1 2.0
# 2 4 5.0
df.loc[:, ['B', 'A']]
# B A
# 1 2.0 1
# 2 5.0 4
df.loc[4, :] = [7, 8, 9.0]
df
# A B C
# 1 1.0 2.0 3
# 2 4.0 5.0 6
# 4 7.0 8.0 9.0
df.loc[:, 'D'] = ['a', 'b', 'c']
df
# A B C D
# 1 1.0 2.0 3 a
# 2 4.0 5.0 6 b
# 4 7.0 8.0 9.0 c
df.loc[4, 'D'] = 'd'
df
# A B C D
# 1 1.0 2.0 3 a
# 2 4.0 5.0 6 b
# 4 7.0 8.0 9.0 d
df = df.drop(index=4, columns='D')
df
# A B C
# 1 1.0 2.0 3
# 2 4.0 5.0 6
지난 교육에서 2주 정도의 진도를 하루 만에 다 나간 것 같다. 한 번 배웠던 내용인데도 겨우 속도를 따라갔던 것 같다. NumPy Pandas는 이후 더 복잡한 내용이 많아지니까 시간 날 때마다 계속 문제를 풀면서 빨리 적응을 해야겠다.