import pandas as pd
sr = pd.Series([17000,18000,1000,5000],
index = ['피자','치킨','콜라','맥주'])
print('시리즈 출력 : ')
print('-' * 15)
print(sr)
시리즈 출력 :
---------------
피자 17000
치킨 18000
콜라 1000
맥주 5000
dtype: int64
print('시리즈의 값 : {}'.format(sr.values))
print('시리즈의 인덱스 : {}'.format(sr.index))
시리즈의 값 : [17000 18000 1000 5000]
시리즈의 인덱스 : Index(['피자', '치킨', '콜라', '맥주'], dtype='object')
values = [[1,2,3],[4,5,6],[7,8,9]]
index = ['one','two','three']
columns = ['A','B','C']
df = pd.DataFrame(values, index=index, columns=columns)
print('데이터 프레임 출력:')
print('-'*18)
print(df)
데이터 프레임 출력:
------------------
A B C
one 1 2 3
two 4 5 6
three 7 8 9
print('데이터프레임의 인덱스 : {}'.format(df.index))
print('데이터프레임의 열이름 : {}'.format(df.columns))
print('데이터프레임의 값 :')
print('-'*18)
print(df.values)
데이터프레임의 인덱스 : Index(['one', 'two', 'three'], dtype='object')
데이터프레임의 열이름 : Index(['A', 'B', 'C'], dtype='object')
데이터프레임의 값 :
------------------
[[1 2 3]
[4 5 6]
[7 8 9]]
data =[
['1000','Steve',90.72],
['1001','James',78.09],
['1002','Doyeon',98.43],
['1003','Jane',64.19],
['1004','Pilwoong',81.30],
['1005','Tony',99.14]
]
df=pd.DataFrame(data)
print(df)
0 1 2
0 1000 Steve 90.72
1 1001 James 78.09
2 1002 Doyeon 98.43
3 1003 Jane 64.19
4 1004 Pilwoong 81.30
5 1005 Tony 99.14
# 생성된 데이터프레임에 열(columns)을 지정
df = pd.DataFrame(data,columns=['학번','이름','점수'])
print(df)
학번 이름 점수
0 1000 Steve 90.72
1 1001 James 78.09
2 1002 Doyeon 98.43
3 1003 Jane 64.19
4 1004 Pilwoong 81.30
5 1005 Tony 99.14
data = {
'학번' : ['1000','1001','1002','1003','1004','1005'],
'이름' : ['Steve','James','Doyeon','Jane','Pilwoong','Tony'],
'점수' : [90.72,78.09,98.43,64.19,81.30,99.14]
}
df = pd.DataFrame(data)
print(df)
학번 이름 점수
0 1000 Steve 90.72
1 1001 James 78.09
2 1002 Doyeon 98.43
3 1003 Jane 64.19
4 1004 Pilwoong 81.30
5 1005 Tony 99.14
아래의 명령어는 데이터프레임에서 원하는 구간만 확인하기 위한 것임.
print(df.head(3))
학번 이름 점수
0 1000 Steve 90.72
1 1001 James 78.09
2 1002 Doyeon 98.43
print(df.tail(3))
학번 이름 점수
3 1003 Jane 64.19
4 1004 Pilwoong 81.30
5 1005 Tony 99.14
print(df['학번'])
0 1000
1 1001
2 1002
3 1003
4 1004
5 1005
Name: 학번, dtype: object
df = pd.read_csv()
import numpy as np
ndarray
vec = np.array([1,2,3,4,5])
print(vec)
[1 2 3 4 5]
array()
안에 하나의 리스트만 들어가므로 리스트의 리스트를 넣어야함. mat = np.array([[10,20,30],[60,70,80]])
print(mat)
[[10 20 30]
[60 70 80]]
print('vec의 타입 : ',type(vec))
print('mat의 타입 : ',type(mat))
vec의 타입 : <class 'numpy.ndarray'>
mat의 타입 : <class 'numpy.ndarray'>
ndim
으로 축의 개수, shape
로 크기를 볼 수 있음. ## vec
print('vec의 축의 개수 : ', vec.ndim) # 축의 개수 출력
print('vec의 크기(shape) : ',vec.shape) # 크기 출력
##mat
print('mat의 축의 개수 :', mat.ndim) #축의 개수 출력
print('mat의 크기(shape) :', mat.shape) #크기 출력
vec의 축의 개수 : 1
vec의 크기(shape) : (5,)
mat의 축의 개수 : 2
mat의 크기(shape) : (2, 3)
ndarray
를 만드는 다양한 방법이 있음. np.zeros()
는 배열의 모든 원소에 0을 삽입함. # 모든 값이 0인 2x3 배열 생성
zero_mat = np.zeros((2,3))
print(zero_mat)
[[0. 0. 0.]
[0. 0. 0.]]
np.ones()
는 배열의 모든 원소에 1을 삽입함. one_mat=np.ones((2,3))
print(one_mat)
[[1. 1. 1.]
[1. 1. 1.]]
np.full()
은 배열에 사용자가 지정한 값을 삽입함. sames_value_mat = np.full((2,2),7)
print(sames_value_mat)
[[7 7]
[7 7]]
np.eye()
는 대각선으로 1이고 나머지는 0인 2차원 배열을 생성함. eye_mat = np.eye(3)
print(eye_mat)
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
np.random.random()
은 임의의 값을 가지는 배열을 생성random_mat = np.random.random((2,2))
print(random_mat)
[[0.80672845 0.30393819]
[0.58899802 0.82808707]]
np.arange(n)
은 0부터 n-1까지의 값을 가지는 배열을 생성range_vec = np.arange(10)
print(range_vec)
[0 1 2 3 4 5 6 7 8 9]
np.arange(i,j,k)
는 i부터 j-1까지 k씩 증가하는 배열을 생성n = 2
range_n_step_vec = np.arange(1,10,n)
print(range_n_step_vec)
[1 3 5 7 9]
np.reshape
은 내부 데이터는 변경하지 않으면서 배열의 구조를 바꿈.arange(30)
을 구행한 후, 5행 6열의 행렬로 변경reshape_mat = np.array(np.arange(30)).reshape((5,6))
print(reshape_mat)
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]]
mat = np.array([[1,2,3],[4,5,6]])
print(mat)
[[1 2 3]
[4 5 6]]
slicing_mat = mat[0, :]
print(slicing_mat)
[1 2 3]
# 두번째 열 출력
slicing_mat = mat[:,1]
print(slicing_mat)
[2 5]
mat = np.array([[1,2],[4,5],[7,8]])
print(mat)
[[1 2]
[4 5]
[7 8]]
# 1행 0열의 원소
print(mat[1,0])
4
# 2행 1열, 0행 1열의 두개의 원소 추출
indexing_mat = mat[[2,1],[0,1]]
print(indexing_mat)
[7 5]
np.add()
np.subtract()
np.multiply()
np.divide()
x = np.array([1,2,3])
y = np.array([4,5,6])
result1 = x + y
result2 = np.add(x,y)
print(result1, result2)
[5 7 9] [5 7 9]
result1 = x - y
result2 = np.subtract(x,y)
print(result1, result2)
[-3 -3 -3] [-3 -3 -3]
result1 = x * y
result2 = np.multiply(x,y)
print(result1, result2)
[ 4 10 18] [ 4 10 18]
result1 = x / y
result2 = np.divide(x,y)
print(result1, result2)
[0.25 0.4 0.5 ] [0.25 0.4 0.5 ]
dot()
을 사용해야함. mat1 = np.array([[1,2],[3,4]])
mat2 = np.array([[5,6],[7,8]])
mat3 = np.dot(mat1,mat2)
print(mat3)
[[19 22]
[43 50]]
import matplotlib.pyplot as plt
plot()
은 라인 플롯을 그리는 기능show()
를 통해 시각화title()
을 통해 제목 지정plt.title('test')
plt.plot([1,2,3,4],[2,4,8,6])
plt.show()
plt.xlabel()
plt.ylabel()
plt.title('test')
plt.plot([1,2,3,4],[2,4,8,6])
plt.xlabel('hours')
plt.ylabel('score')
plt.show()
legend()
를 사용하여 범례를 볼 수 있음. plt.title('students')
plt.plot([1,2,3,4],[2,4,8,6])
plt.plot([1.5,2.5,3.5,4.5],[3,5,8,10])
plt.xlabel('hours')
plt.ylabel('score')
plt.legend(['A student','B student'])
plt.show()