데이터 분석을 위해 파이썬에서는 Pandas와 Numpy 그리고 Matplotlib를 제공한다. 이 글에서는 matplotlib 을 사용해 보겠다. matplotlib는 python에서 다양한 시각화 기술을 구현하는 라이브러리이다.

 

먼저 matplotlib을 사용하기 위해서는 아래와 같이 import 선언을 해주어야 한다.

필자는 matplotlib패키지의 pyplot모듈을 사용하기 위해 plt라는 객체명을 선언하였다.

import matplotlib.pyplot as plt

 

numpy를 사용하여 배열을 먼저 생성해보자

import numpy as np

x = np.arange(-4.5, 5, 0.5)
y = 2 * x ** 2
[x,y]

->
[array([-4.5, -4. , -3.5, -3. , -2.5, -2. , -1.5, -1. , -0.5,  0. ,  0.5,
         1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5]),
 array([40.5, 32. , 24.5, 18. , 12.5,  8. ,  4.5,  2. ,  0.5,  0. ,  0.5,
         2. ,  4.5,  8. , 12.5, 18. , 24.5, 32. , 40.5])]

 

show() - 그래프 그리기

위 생성된 배열을 각각 x, y 값으로 그래프로 표현해보자

plt.plot(x,y)
plt.show()

 

 

 

 

 


figure(), subplot()

x = np.arange(-4.5, 5, 0.5)
y1 = 2*x**2
y2 = 5*x + 30
y3 = 4*x**2 + 10
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.show()

 

plt.plot(x, y1)

plt.figure()
plt.plot(x,y2)

plt.show()

 

 

x = np.arange(-5, 5, 0.1)
y1 = x**2 -2
y2 = 20 * np.cos(x)**2

plt.figure(1) #1번 그래프 창 생성
plt.plot(x, y1)
plt.figure(2) #2번 그래프 창 생성
plt.plot(x, y2)
plt.figure(1) # 이미 생성된 1번 그래프 창을 지정
plt.plot(x, y2)
plt.figure(2) #이미 생성된 2번 그래프 창을 지정
plt.clf() # 2번 그래프 창에 그려진 모든 그래프를 지움
plt.plot(x,y1) #지정된 그래프 창에 그래프를 그림
plt.show()

 

x = np.arange(0, 10, 0.1)
y1 = 0.3*(x-5)**2 + 1
y2 = -1.5*x +3
y3 = np.sin(x)**2
y4 = 10*np.exp(-x) + 1
# 2x2 행렬로 이루어진 서브 그래프에서 p에 따라 위치를 지정
plt.subplot(2,2,1) # p는 1
plt.plot(x,y1)
plt.subplot(2,2,2) # p는 2
plt.plot(x,y2)
plt.subplot(2,2,3) # p는 3
plt.plot(x,y3)
plt.subplot(2,2,4) # p는 4
plt.plot(x,y4)
plt.show()

 


xlim(), xlim() - 그래프의 x축, y축의 범위 설정

x = np.linspace(-4, 4, 100)
y1 = x**3
y2 = 10*x**2 -2

plt.plot(x,y1,x,y2)
plt.xlim(-1,1) # x축의 범위를 -1에서 1로 한정
plt.ylim(-3,3) # y축의 범위를 -3에서 3로 한정
plt.show()

 


그래프 그리기 예시

import matplotlib

matplotlib.rcParams['font.family'] = 'Malgun Gothic'
matplotlib.rcParams['axes.unicode_minus'] = False
plt.plot(x, y1, '>--r', x, y2, 's-g', x, y3, 'd:b', x, y4, '-.Xc')
plt.legend(['데이터1', '데이터2', '데이터3', '데이터4'], loc = 'best')
plt.xlabel('X 축')
plt.ylabel('Y 축')
plt.title('그래프 제목')
plt.grid(True)

 


import matplotlib.pyplot as plt

height = [165,177,160,180,185,155,172]
weight = [62,67,55,74,90,43,64]

plt.scatter(height, weight)
plt.xlabel('Height(m)')
plt.ylabel('Weight(Kg)')
plt.title('Height & Weight')
plt.grid(True)

plt.scatter(height, weight, s=500, c='r')
plt.show()

 


city = ['서울', '인천', '대전', '대구', '울산', '부산', '광주']
# 위도(latitude)와 경도(longitude)
lat = [37.56,37.45,36.35,35.87,35.53,35.18,35.16]
lon = [126.97,126.70,127.38,128.60,129.31,129.07,126.85]
#인구 밀도(명/km^2): 2017년 통계청 자료
pop_den = [16154,2751,2839,2790,1099,4454,2995]

size = np.array(pop_den) * 0.2 # 마커의 크기 지정
colors = ['r', 'g', 'b', 'c', 'm', 'k', 'y'] # 마커의 컬러지정
plt.scatter(lon, lat, s=size, c=colors, alpha=0.5)
plt.xlabel('경도(longitude)')
plt.ylabel('위도(latitude)')
plt.title('지역별 인구 밀도(2017)')

for x, y, name in zip(lon, lat, city):
    plt.text(x, y, name) # 위도 경도에 맞게 도시 이름 출력
plt.show()


member_IDs = ['m_01', 'm_02', 'm_03', 'm_04']
before_ex = [27, 35, 40, 33]
after_ex = [30,38,42,37]
n_data = len(member_IDs)
index = np.arange(n_data)
plt.bar(index, before_ex)
plt.show()

 

barWidth = 0.4
plt.bar(index, before_ex, color='c', align='edge', width = barWidth, label='before')
plt.bar(index + barWidth, after_ex, color='m', align='edge', width = barWidth, label='after')

plt.xticks(index + barWidth, member_IDs)
plt.legend()
plt.xlabel('회원 ID')
plt.ylabel('위몸일으키기 횟수')
plt.title('운동 시작 전과 후의 근지구력(복근) 변화 비교')
plt.show()

 


fruit = ['사과', '바나나', '딸기', '오렌지', '포도']
result = [7,6,3,2,2]
plt.pie(result)
plt.show()

 

plt.figure(figsize=(5,5))
plt.pie(result, labels = fruit, autopct='%.1f%%')
plt.show()

explode_value = (0.1,0,0,0,0)

plt.figure(figsize=(5,5))
plt.pie(result, labels=fruit, autopct='%.1f%%', startangle=90, counterclock=False, explode=explode_value, shadow=True)
plt.show()

 

 

 


import pandas as pd

temperature = [25.2,27.4,22.9,26.2,29.5,33.1,30.4,36.1,34.4,29.1]
Ice_cream_sales = [236500,357500,203500,365200,446600,574200,453200,675400,598400,463100]

dict_data = {'기온':temperature, '아이스크림 판매량':Ice_cream_sales}
df_ice_cream = pd.DataFrame(dict_data, columns=['기온', '아이스크림 판매량'])
df_ice_cream

 

df_ice_cream.plot.scatter(x='기온', y='아이스크림 판매량', grid=True, title='최고 기온과 아이스크림 판매량')
plt.show()

 

matplotlib-1.html
1.07MB

 

 


wordcloud를 이용한 데이터 통계

import pandas as pd

word_count_file = "C:/pywork/word_count.csv"
word_count = pd.read_csv(word_count_file, index_col = '단어')
word_count.head(5)

->
	빈도
단어	
산업혁명	1662
기술	1223
사업	1126
혁신	1084
경제	1000
from wordcloud import WordCloud
import matplotlib.pyplot as plt

korean_font_path = 'C:/Windows/Fonts/malgun.ttf'
wc = WordCloud(font_path=korean_font_path, background_color='white')

frequencies = word_count['빈도'] # pandas의 Series 형식
wordcloud_image = wc.generate_from_frequencies(frequencies)
wc = WordCloud(font_path=korean_font_path, background_color='white')

frequencies = word_count['빈도'] # pandas의 Series 형식
wordcloud_image = wc.generate_from_frequencies(frequencies)

 

matplotlib-2.html
0.61MB

 

반응형

데이터 분석을 위해 파이썬에서는 Pandas와 Numpy 그리고 Matplotlib를 제공한다. 이 글에서는 pandas의 함수사용법에 대해 알아보겠다. pandas는 파이썬의 데이터 처리를 위한 라이브러리이다.

 

 

pandas를 사용하기 위해서는 pandas모듈을 import를 해야한다. 보통 pd라는 별칭으로 사용한다.

import pandas as pd
import numpy as np

 

Series() - 시리즈는 1차원 배열의 값(values)에 각 값에 대응되는 인덱스(index)를 부여할 수 있는 구조를 갖는다

s5 = pd.Series({'국어':100, '영어':95, '수학':90})
s5
->
국어    100
영어     95
수학     90
dtype: int64
index_date = ['2018-10-07', '2018-10-08', '2018-10-09', '2018-10-10']
s4 = pd.Series([200, 195, np.nan, 205], index = index_date)
s4

->
2018-10-07    200.0
2018-10-08    195.0
2018-10-09      NaN
2018-10-10    205.0
dtype: float64

 

date_range() - 날짜 범위 만들기

(freq='D'로 선언하면 day를 기준으로 날짜를 나누겠다는 뜻 -> periods=5로 선언되어 있으므로 시작날짜 2021-02-01부터 5일을 부여하겠다는 의미 / freq는 생략 가능한데 생략할 시 default 값은 'D'(day))

index_date = pd.date_range(start = '2021-02-01', periods = 5, freq='D')
pd.Series([51,62,55,49,58], index = index_date)

->
2021-02-01    51
2021-02-02    62
2021-02-03    55
2021-02-04    49
2021-02-05    58
Freq: D, dtype: int64

 

 

DataFrame() - 2차원 데이터 테이블 구조를 가지는 자료형.

데이터프레임은 2차원 리스트를 매개변수로 전달한다. 2차원이므로 행방향 인덱스(index)와 열방향 인덱스(column)가 존재한다. 즉, 행과 열을 가지는 자료구조이다. 시리즈가 인덱스(index)와 값(values)으로 구성된다면, 데이터프레임은 열(columns)까지 추가되어 열(columns), 인덱스(index), 값(values)으로 구성된다.

data = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
index_date = pd.date_range('2019-09-01', periods=4)
columns_list = ['A', 'B', 'C']
pd.DataFrame(data, index=index_date, columns=columns_list)

->
		A	B	C
2019-09-01	1	2	3
2019-09-02	4	5	6
2019-09-03	7	8	9
2019-09-04	10	11	12
table_data3 = {'봄': [256.5,264.3,215.9,223.2,312.8],
              '여름': [770.6,567.5,599.8,387.1,446.2],
              '가을': [363.5,231.2,293.1,247.7,381.6],
              '겨울': [139.3,59.9,76.9,109.1,108.1]}
columns_list = ['봄', '여름', '가을', '겨울']
index_list = ['2012', '2013', '2014', '2015', '2016']

df3 = pd.DataFrame(table_data3, columns = columns_list, index = index_list)
df3

->
	봄	여름	가을	겨울
2012	256.5	770.6	363.5	139.3
2013	264.3	567.5	231.2	59.9
2014	215.9	599.8	293.1	76.9
2015	223.2	387.1	247.7	109.1
2016	312.8	446.2	381.6	108.1

 

 

mean() - 평균 구하기 (axis=1 이면, 행 기준)

df3.mean()
->
봄     254.54
여름    554.24
가을    303.42
겨울     98.66
dtype: float64
df3.mean(axis=1)
->
2012    382.475
2013    280.725
2014    296.425
2015    241.775
2016    312.175
dtype: float64

 

describe() - 데이터 요약

df3.describe()
->
	봄		여름		가을		겨울
count	5.000000	5.000000	5.000000	5.000000
mean	254.540000	554.240000	303.420000	98.660000
std	38.628267	148.888895	67.358496	30.925523
min	215.900000	387.100000	231.200000	59.900000
25%	223.200000	446.200000	247.700000	76.900000
50%	256.500000	567.500000	293.100000	108.100000
75%	264.300000	599.800000	363.500000	109.100000
max	312.800000	770.600000	381.600000	139.300000

 

 

 

 

 

 

데이터 조회

KTX_data = {'경부선 KTX': [39060,39896,42005,43621,41702,41266,32427],
            '호남선 KTX': [7313,6967,6873,6626,8675,10622,9228],
            '경전선 KTX': [3627,4168,4088,4424,4606,4984,5570],
            '전라선 KTX': [309,1771,1954,2244,3146,3945,5766],
            '동해선 KTX': [np.nan,np.nan,np.nan,np.nan,2395,3786,6667]}
col_list = ['경부선 KTX', '호남선 KTX', '경전선 KTX', '전라선 KTX', '동해선 KTX']
index_list = ['2011', '2012', '2013', '2014', '2015', '2016', '2017']

df_KTX = pd.DataFrame(KTX_data, columns = col_list, index = index_list)
df_KTX

 

 

행 기준 indexing

df_KTX[1:2]

 

 

index 또는 column 명으로 조회

df_KTX.loc['2013':'2016']

 

df_KTX['경부선 KTX']['2012':'2014']

->
2012    39896
2013    42005
2014    43621
Name: 경부선 KTX, dtype: int64

 

.T - 행과 열 바꾸기

df_KTX.T # T -> 행과 열 바꾸기

 

 

append() - 테이블 붙이기

(ignore_index=True 일 경우 붙임 당하는 테이블의 index를 이어서 적용한다 (속성 생략 가능))

df1 = pd.DataFrame({'Class1':[95,92,98,100],
                    'Class2':[91,93,97,99]})
df1

->
	Class1	Class2
0	95	91
1	92	93
2	98	97
3	100	99
df2 = pd.DataFrame({'Class1': [87,89],
                   'Class2': [85,90]})
df2

->
	Class1	Class2
0	87	85
1	89	90
df1.append(df2, ignore_index=True)

->
	Class1	Class2
0	95	91
1	92	93
2	98	97
3	100	99
4	87	85
5	89	90

 

 

 

 

join() - 테이블 합치기

index_label = ['a','b','c','d']
df1a = pd.DataFrame({'Class1':[95,92,98,100],
                    'Class2':[91,93,97,99]}, index=index_label)
df5 = pd.DataFrame({'Class4':[82,92]})
df1.join(df5)

->
	Class1	Class2	Class4
0	95	91	82.0
1	92	93	92.0
2	98	97	NaN
3	100	99	NaN

 

 

merge() - 테이블 결합

df_left = pd.DataFrame({'key':['A','B','C'], 'left':[1,2,3]})
df_left

->
	key	left
0	A	1
1	B	2
2	C	3
df_right = pd.DataFrame({'key':['A','B','D'], 'right':[4,5,6]})
df_right

->
	key	right
0	A	4
1	B	5
2	D	6

 

#df_left를 기준(how='left')(df_left가 merge왼쪽에 있으므로)을 두고 on='key'에서 속성 값인 key(컬럼)를 비교하여 key(컬럼)가 일치하거나 left의 key만 있는경우 결합

df_left.merge(df_right, how='left', on='key') 

->
	key	left	right
0	A	1	4.0
1	B	2	5.0
2	C	3	NaN

 

#df_right를 기준(how='right')(df_right가 merge오른쪽에 있으므로)을 두고 on='key'에서 속성 값인 key(컬럼)를 비교하여 key(컬럼)가 일치하거나 right의 key만 있는경우 결합

df_left.merge(df_right, how='right', on='key') 

->
	key	left	right
0	A	1.0	4
1	B	2.0	5
2	D	NaN	6

 

df_left.merge(df_right, how='outer', on='key') 

->
	key	left	right
0	A	1.0	4.0
1	B	2.0	5.0
2	C	3.0	NaN
3	D	NaN	6.0
df_left.merge(df_right, how='inner', on='key')

->
	key	left	right
0	A	1	4
1	B	2	5

 

 

pandas.html
0.66MB

 

 

 

반응형

Numpy는 Python에서 벡터, 행렬 등 수치 연산을 수행하는 선형대수 라이브러리이다.

Numpy에서는 모든 배열의 값이 기본적으로 같은 타입이어야 한다. 때문에 서로 다른 데이터들로 구성되어있는 array 일 경우 같은 자료형의 데이터로 맞추거나 자료형 맞추는것이 불가능 한 경우는 오류가 발생한다

(Numpy에서 array를 행렬로 봐야함)


list를 array로 변경

import numpy as np
data1 = [0,1,2,3,4,5]
a1 = np.array(data1)
a1

->
array([0, 1, 2, 3, 4, 5])
data2 = [0.1, 5, 4, 12, 0.5]
a2 = np.array(data2)
a2

->
array([ 0.1,  5. ,  4. , 12. ,  0.5])
a1.dtype

->
dtype('int32')
#int형 32비트
a2.dtype

->
dtype('float64')

 


arange() - 특정 범위 내에서 일정한 간격의 데이터 배열 생성

arange(start, stop, step, dtype) -> start, step, dtype 생략 가능 (dtype 생략 시 다른 매개변수로부터 type을 추론한다)

np.arange(0, 10, 2)

->
array([0, 2, 4, 6, 8])
np.arange(1, 10)

->
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
np.arange(5)

->
array([0, 1, 2, 3, 4])

 


reshape() - 다차원 변환

np.arange(12).reshape(4,3)

->
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

 


#shape -> 배열 각 축의 크기

b1 = np.arange(12).reshape(4,3)
b1.shape

->
(4, 3)
#4행3열의 배열
b2 = np.arange(5)
np.arange(5)
->
array([0, 1, 2, 3, 4])


b2.shape
->
(5,)
# 5개의 열을 가지는 배열

 


linspace() - 일정한 간격의 데이터를 가지는 배열 만들기

np.linspace(start, stop, num, endpoint=True) -> 마지막 endpoint=True 또는 False로 줄 수 있는데 Default는 True이다. True일 경우 stop값을 포함하고 False일 경우는 포함하지 않는다는 옵션이다.

np.linspace(1, 10, 10)
->
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
np.linspace(1, 10, 10, endpoint=False)
->
array([1. , 1.9, 2.8, 3.7, 4.6, 5.5, 6.4, 7.3, 8.2, 9.1])
np.linspace(0, np.pi, 20)
->
array([0.        , 0.16534698, 0.33069396, 0.49604095, 0.66138793,
       0.82673491, 0.99208189, 1.15742887, 1.32277585, 1.48812284,
       1.65346982, 1.8188168 , 1.98416378, 2.14951076, 2.31485774,
       2.48020473, 2.64555171, 2.81089869, 2.97624567, 3.14159265])

 


eye() - 단위 행렬 만들기

np.eye(3) #단위 행렬(특수 배열)
->
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

 


zeros() - 모두 0으로 된 배열 생성

np.zeros(10)
->
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
np.zeros((3,4))
->
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

 


astype() - 데이터프레임 타입 바꾸기

str_a1 = np.array(['1.567', '0.123', '5.123', '9', '8'])
num_a1 = str_a1.astype(float)
num_a1

->
array([1.567, 0.123, 5.123, 9.   , 8.   ])

 


sum() - 합계, mean() - 평균, std() - 표준편차, var() - 분산

arr3 = np.arange(5)
arr3
->
array([0, 1, 2, 3, 4])

[arr3.sum(), arr3.mean(), arr3.std(), arr3.var()]
->
[10, 2.0, 1.4142135623730951, 2.0]

 

cumsum(), cumprod()

 

반응형

파일을 생성하거나 읽고 쓰는 경우 아래와 같이 현재 위치를 원하는 폴더로 지정해 놓아야 한다

(필자는 Python 저장 경로는 c드라이브의 pywork라는 폴더로 설정했다)

cd C:\pywork

 

myFile.txt파일을 생성하고 write('w')할 수 있는 객체 f 생성 후 내용 작성

f = open('myFile.txt', 'w')
f.write('This is my first file.')
f.close()

 

myFile.txt를 read('r')할 수 있는 객체 f 생성 후 내용 읽기

f = open('myFile.txt', 'r')
file_text = f.read()
f.close()
print(file_text)

->
This is my first file.

 

 

위와 같은 방법으로 파일 생성 후 다른 내용을 담아 보았다

f = open('two_times_table.txt', 'w')
for num in range(1,6):
    format_string = "2 x {0} = {1}\n".format(num, 2*num)
    f.write(format_string)
f.close()
f = open("two_times_table.txt")
line = f.readline()
while line:
    print(line, end = "")
    line = f.readline()
f.close()

->
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

 

# lines = f.readlines() -> list형식으로 담김

f = open("two_times_table.txt")
lines = f.readlines()
f.close()
print(lines)

->
['2 x 1 = 2\n', '2 x 2 = 4\n', '2 x 3 = 6\n', '2 x 4 = 8\n', '2 x 5 = 10\n']

 

 

f = open("two_times_table.txt")
lines = f.readlines()
f.close()
for line in lines:
    print(line, end="")
    
->
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

 

 

파일을 담은 객체를 그대로 사용 (코드 간소화)

f = open("two_times_table.txt")
for line in f:
    print(line, end="")
f.close()

->
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

 

with as 키워드 사용

파일을 다루는 처리를 할때는 필수적으로 파일 오픈(open) 파일 닫기(close) 과정을 거치게 되는데 실수로 close하지 않는 경우가 종종 발생한다. 이런 경우를 대비해 with as 구문을 사용하여 해당 구문이 끝나면 자동으로 닫히게 되어서 이러한 실수를 줄일 수 있다

with open('myTextFile3.txt', 'w') as f:
    for num in range(1, 6):
        format_str = "3 x {0} = {1}\n".format(num, 3*num)
        f.write(format_str)
with open('myTextFile3.txt', 'r') as f:
    for line in f:
        print(line, end="")
        
->
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
반응형

Python 파일(.py) 저장

 

먼저, 저장하고 싶은 경로에 폴더를 생성한다(C드라이브에 pywork폴더)

그리고 아래와 같이 상단에 %%writefile C:\pywork\my_area.py 라는 명령문을 입력한다

%%는 아나콘다 시스템 명령에 사용된다

%%writefile C:\pywork\my_area.py
    
PI = 3.14
    
def square_area(a):
    return a ** 2 #정사각형 넓이

def circle_area(r):
    return PI * r ** 2 # 원의 넓이
    
->
Writing C:\pywork\my_area.py

따라서 위처럼 코드를 작성하면 

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

PI = 3.14
    
def square_area(a):
    return a ** 2 #정사각형 넓이

def circle_area(r):
    return PI * r ** 2 # 원의 넓이

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

이 내용을 담은 my_area.py파일이 pywork폴더에 생성된다.

 

 

 

 

폴더(directory) 생성

mkdir C:\pywork\image; C:\pywork\image\io_file

# image폴더 안에 io_file폴더 생성

반응형

split() - 문자열 나누기

coffee_menu_str = "에스프레소, 아메리카노, 카페라테, 카푸치노"
coffee_menu_str.split(',')

-> ['에스프레소', ' 아메리카노', ' 카페라테', ' 카푸치노']
" 에스프레소 \n\n 아메리카노 \n 카페라테 카푸치노 \n\n".split()

-> ['에스프레소', '아메리카노', '카페라테', '카푸치노']
"에스프레소 아메리카노 카페라테 카푸치노 말차프라페".split(maxsplit=2)

-> ['에스프레소', '아메리카노', '카페라테 카푸치노 말차프라페']
phone_number = "+82-01-2345-6789" #국가 번호가 포함된 전화번호
split_num = phone_number.split("-", 1) #국가 번호와 나머지 번호 분리

print(split_num)
print("국내전화번호: {0}".format(split_num[1]))

->['+82', '01-2345-6789']
국내전화번호: 01-2345-6789

 


strip() - 문자열 앞뒤의 해당 문자 제거 (주의 : 앞뒤만)

test_str = "aaabbPythonbbbaa"
temp1 = test_str.strip('a') # 문자열 앞뒤의 'a' 제거
temp1

->'bbPythonbbb'

temp1.strip('b')

-> 'Python'
test_str_multi = "##***!!!##.... Python is powerful.!... %%!#..   "
test_str_multi.strip('*.#! %')

-> 'Python is powerful'
"\n This is very \n fast. \n\n".strip()

-> 'This is very \n fast.'

 


split(), strip() 활용

coffee_menu = " 에스프레소, 아메리카노,    카페라테   ,   카푸치노   "
coffee_menu_list = coffee_menu.split(',')

coffee_list = [] # 빈 리스트 생성
for coffee in coffee_menu_list:
    temp = coffee.strip() # 문자열의 공백 제거
    coffee_list.append(temp) # 리스트 변수에 추가
print(coffee_list) # 최종 리스트 출력

-> ['에스프레소', '아메리카노', '카페라테', '카푸치노']

 


find() - 문자열 찾기

tr_f = "Python code."

print("찾는 문자열의 위치:", str_f.find("Python"))
print("찾는 문자열의 위치:", str_f.find("code"))
print("찾는 문자열의 위치:", str_f.find("n"))
print("찾는 문자열의 위치:", str_f.find("easy")) #easy라는 문자열 존재 하지 않음 -> -1 반환

->
찾는 문자열의 위치: 0
찾는 문자열의 위치: 7
찾는 문자열의 위치: 5
찾는 문자열의 위치: -1
str_f_se = "Python is powerful, Python is easy to learn."

print(str_f_se.find("Python", 10, 30)) #시작 위치(start)와 끝 위치(end) 지정
print(str_f_se.find("Python", 35)) #찾기 위한 시작 위치(start) 지정

->
20
-1

 


startswith(), endswith() - 시작과 끝의 문자열이 해당 문자열인지 확인

str_se = "Python is pwerful, Python is easy to learn."

print("Python으로 시작?:", str_se.startswith("Python"))
print("is로 시작?:", str_se.startswith("is"))
print(".로 끝?:", str_se.endswith("."))
print("learn으로 끝?:", str_se.endswith("learn"))

->
Python으로 시작?: True
is로 시작?: False
.로 끝?: True
learn으로 끝?: False

 

 

 


replace() -  문자열 대체하기

str_a = 'Python is fast. Python is friendly. Python is open.'
print(str_a.replace('Python', 'IPython'))
print(str_a.replace('Python', 'IPython', 2))

->
IPython is fast. IPython is friendly. IPython is open.
IPython is fast. IPython is friendly. Python is open.

 

 


isalnum(), isspace()

print('acb1234'.isalnum()) #특수 문자나 공백이 아닌 문자와 숫자로 구성됨
print('    acb1234'.isalnum()) #문자열에 공백이 있음
print('    '.isspace()) #문자열이 공백으로만 구성됨
print('  1  '.isspace()) #문자열에 공백 외에 다른 문자가 있음

->
True
False
True
False

 

 

 

반응형

리스트(list)

요소를 삭제하거나 변경 가능(mutable(가변성)) ->append, del, remove, pop ...

서로 다른 type의 데이터를 담을 수 있다

list안에 list로 element를 표현할 수 있다.

list_data = [0,1,2,3,4,5,6,7,8,9]
del list_data[6]
print(list_data) -> [0, 1, 2, 3, 4, 5, 7, 8, 9]

 

insert() - 특정한 위치(인덱스)에 원소를 삽입

myFriends = ['James', 'Robert', 'List', 'Mary']
myFriends.insert(1, 'Pau)
print(myFriends) -> ['James', 'Paul', 'Robert', 'List', 'Mary']

 

remove() - 리스트 내 특정 원소를 삭제

pop() - 리스트 내 특정 인덱스의 원소를 삭제

a = [10,20,30,40,50,60,70,80,90,100]
a.pop(3) #del a[3] 와 동일
a.remove(90)
print(a) -> [10, 20, 30, 50, 60, 70, 80, 100]

 

List Sliding

[start:stop:step]
start : 시작index번호
stop : 끝나는 index번호(단, 포함하지 않음)
step : index간 step(간격)

list_data = [0,1,2,3,4,5,6,7,8,9]
print(list_data[:3])
print(list_data[7:])
print(list_data[::2])
print(list_data[::3])
print(list_data[1::2])
print(list_data[1:5:3])

[0, 1, 2]
[7, 8, 9]
[0, 2, 4, 6, 8]
[0, 3, 6, 9]
[1, 3, 5, 7, 9]
[1, 4]

 

append() - 리스트의 뒤에 새로운 원소를 삽입

a = [1, 2, 3]
a.append(4)
a
-> [1, 2, 3, 4]
a.append([5,6])
a
-> [1, 2, 3, 4, [5, 6]]

 

extend() - 리스트의 뒤쪽에 다른 리스트를 삽입

(extend(x)에서 x는 리스트만 올 수 있음, 원래의 a 리스트에 x 리스트를 더함)

a = [1,2,3]
a.extend([4,5])
a
-> [1, 2, 3, 4, 5]
b = [6, 7]
a.extend(b)
a
-> [1, 2, 3, 4, 5, 6, 7]

 

sort() - 리스트를 오름차순으로 정렬

list2 = [1, 5, 13, 8, 3, -7, 9, 11]
list2.sort()
print(list2)
-> [-7, 1, 3, 5, 8, 9, 11, 13]
list2.sort(reverse=True)
print(list2)
-> [13, 11, 9, 8, 5, 3, 1, -7]

 

index() - 리스트 내 특정 원소의 인덱스를 반환

a = [1,2,3]
a.index(3)
-> 2
a.index(1)
-> 0

 

count() - 리스트 내 특정 원소가 몇 개 포함되어 있는지 반환

a = [1,2,3,1]
a.count(1)
2

 


튜플(tuple)

list와 비슷하지만 요소를 삭제하거나 변경 불가능한 면에서 다르다 (immutable(불변성))

 

 # 투플의 요소는 변경 불가

tuple5[1] = 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-35d2428361b3> in <module>
----> 1 tuple5[1] = 5 # 투플의 요소는 변경 불가

TypeError: 'tuple' object does not support item assignment

 

count()

tuple7 = ('a','a','a','b','b','c','d')
tuple7.count('a')
-> 3

 

len() - 길이 

t1 = (1, 2, 'a', 'b')
len(t1)
-> 4

 


셋(set)

Set은 python 2.3부터 지원한 자료형으로, 집합에 관련된 것을 쉽게 처리하기 위해 만든 자료형이다

#중복 값을 갖지 못함

set1 = {1,2,3}
set1a = {1,2,3,3}
print(set1)
print(set1a)
-> {1, 2, 3}
-> {1, 2, 3}

 

set 활용 / 형변환

a = [1,2,3,4,5,5,5]
b = tuple(a)
c = set(a)
type(a)
-> list
b
-> (1, 2, 3, 4, 5, 5, 5)
c
-> {1, 2, 3, 4, 5}
type(c)
-> set

 


딕셔너리(dict)

데이터가 다양해지고 속성과 값들의 표현들이 많아져 단순 List나 tuple로 데이터를 표현하기가 힘들기 때문에 데이터들의 대응관계(속성과 값)를 나타낼 때는 딕셔너리(Dictionary)를 사용하는 것이 좋다

 

특정 key값에 대한 value값 뽑기

dict_data2 = {1:10, 2:20, 3:30, 4:40, 5:50}
print(dict_data2)
print(dict_data2[4])
-> {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
-> 40

 

value값에 list와 tuple을 넣을 수 있다. 하지만 key에는 tuple만 사용할 수 있다.

(list는 값이 변할 수 있기 때문에 key값으로 사용할 수 없다.)

mixed_dict = {1:10, 'dict_num' : {1:10, 2:20}, "dict_list_tuple" : {"A" : [11,12,13], "B" : (21,22,23)}, "dict_string" : "이것은 책입니다."}
mixed_dict
-> {1: 10,
 'dict_num': {1: 10, 2: 20},
 'dict_list_tuple': {'A': [11, 12, 13], 'B': (21, 22, 23)},
 'dict_string': '이것은 책입니다.'}

 

key-value 값 추가

country_capital = {"영국":"런던", "프랑스":"파리", "스위스":"베른","호주":"캔버라"}

country_capital["독일"]="베를린"
country_capital
-> {'영국': '런던', '프랑스': '파리', '스위스': '베른', '호주': '캔버라', '독일': '베를린'}

 

value값 변경

country_capital["호주"]="캔버라~"
country_capital
-> {'영국': '런던', '프랑스': '파리', '스위스': '베른', '호주': '캔버라~', '독일': '베를린'}

 

keys() - key값 뽑기

fruit_code = {"사과":101, "배":102, "딸기":103, "포도":104, "바나나":105}

print(fruit_code.keys())
-> dict_keys(['사과', '배', '딸기', '포도', '바나나'])

 

values() - value값 뽑기

print(fruit_code.values())
-> dict_values([101, 102, 103, 104, 105])

 

item() - Key와 Value의 쌍을 튜플로 묶은 값을 dict_items 객체로 반환

fruit_code.items()
-> dict_items([('사과', 101), ('배', 102), ('딸기', 103), ('포도', 104), ('바나나', 105)])
list(fruit_code.items())
-> [('사과', 101), ('배', 102), ('딸기', 103), ('포도', 104), ('바나나', 105)]

 

update() - 값 변경 또는 추가

(update받는 dict쪽에 해당 key값이 없으면 key-value가 추가되고 key값이 존재하면 대응되는 value값이 수정된다)

fruit_code = {"사과":101, "배":102, "딸기":103, "포도":104, "바나나":105}
fruit_code2 = {"오렌지":106, "수박":107}

fruit_code.update(fruit_code2)
fruit_code

-> {'사과': 101, '배': 102, '딸기': 103, '포도': 104, '바나나': 105, '오렌지': 106, '수박': 107}

 

key-value 삭제

del fruit_code2['수박']
fruit_code2
-> {'오렌지': 106}

 

in

a = {'name':'Jim', 'phone':'01012341234', 'birth': '0521'}
'name' in a
True
'email' in a
False
반응형

+ Recent posts