Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
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 30
Tags
more
Archives
Today
Total
관리 메뉴

BASEMENT

Python 7주차 - 2 본문

Programming/Python

Python 7주차 - 2

2_34 2020. 8. 3. 09:14

 

파이썬 실습

 

1. 리스트 중에서 i번째 숫자부터 j번째 숫자까지를 슬라이싱한 후 k번째에 있는 수를 찾아 출력

- 리스트 길이는 1이상 50이하

- 리스트의 각 원소 범위는 1이상 100이하

- 자르는 행위는 1이상 10이하

ex) [2,44,73,54,23,29,85,34] : 원본리스트

     [[6,8,2], [4,8,5]] : commands

     [34,85] : return값

import random

def nst_N(*args):
    origin,s,e,k = args
    result = sorted(origin[s-1:e])[k-1]
    return result
    
# def nst_N(*args):
#	origin, command = argsreturn list(map(lambda x:sorted(origin[x[0]-1:x[1]])[x[2]-1], command))    

if __name__ == "__main__":
    ary_n = random.randint(1,50)
    origin = [random.randrange(1,100) for i in range(ary_n)]
    commands = random.randint(1,10)

    result = []
    command = []
    for i in range(commands):
        ary_start = random.randint(1, ary_n)
        ary_end = random.randint(ary_start, ary_n)
        k = random.randint(1, ary_end-ary_start+1)
        result.append(nst_N(origin, ary_start, ary_end, k))
        command.append([ary_start, ary_end, k])
    print(origin, command, result)

 

2. 주어진 문장에서 "encore" 또는 "엔코어" 찾기

- 문장은 input 함수로 입력

- 입력된 문장을 공백기준으로 분할 후 리스트에 저장

- 리스트에서 encore 또는 엔코어를 찾고, 위치값을 함께 반환

ex) enter a sentence >> I hope your skills improve through encore.

    (['I', 'hope', 'your', 'skills', 'improve', 'through', 'encore'], [6])

def word_search(string):
    splits = string.strip('.').split()
    result = []
    for index, word in enumerate(splits):
        if word =='encore' or word =="엔코어":
            result.append(index)
        return splits, result

string = input("enter a sentence>> ")
print(word_search(string))

 

3. 콜라츠(Collatz) 추측

주어진 수가 1이 될때까지 다음 작업을 반복하여 모든 수를 1로 만들 수 있다는 추측

- 입력된 수가 짝수면 2로 나눔

-  입력된 수가 홀수면 3을 곱하고 1을 더함

- 결과로 나온 수에 같은 작업을 1이 될 때까지 반복

반복의 수가 500이 되도록 1이 되지 못하면 -1을 반환

ex) 6이 입력되면 , 6->3->10->5->16->8->4->2->1 로 8번 만에 1이 됨

def collatze(num):
    count = 0

    while True:
        if num != 1:
            if num%2 == 0:
                num = num/2
                count += 1
            else:
                num = num*3 + 1
                count += 1
        elif count == 500:
            return -1
        else:
            return count
            break
            
def collatz(num):
    count = -1
    for i in range(500):
        if num == 1:
            return i
        if num%2 == 0: 
            num //= 2
        else:
            num = num*3 + 1
    return count

if __name__ == "__main__":
    n = int(input("enter positive integer >> "))
    pdb.set_trace()
    print(f'{n}은 {collatz(n)} 번만에 1이 됨')            

num = int(input("enter positive integer >> "))
print(collatze(num))

# 재귀함수
def collatz(num):
	global count
    if num == 1:
    	return count
    else:
        count += 1
        return collatz(num//2) if num%2 ==0 else collatz(num*3+1)

count = 0
num = int(input("enter positive integer >> "))
def collatz(num)

 

 

4. 연도를 입력하면 윤년인지 아닌지 판별

- 윤년 : 2월이 29일인 해

- 4로 나누었을때 나머지가 0이면서, 100으로 나누었을때 나머지가 0이 아닌 해

- 또는 400으로 나누었을때 나머지가 0인 해

def solution(year):
    if (year%4 == 0 and year%100 != 0) or year%400 == 0 :
        return print("윤년입니다")
    else:
        return print("평년입니다")

if __name__ == "__main__":
    while True:
        year = int(input("enter year >> "))
        if year <= 0:
            break
        solution(year)

 

 

Pandas

1. Series

 

index와 value로 구성된 pandas의 기본 데이터

배열과 유사하나, 인덱스 조정이 가능하므로 검색 시 배열보다 편리함

import pandas as pd
import numpy as np

srs1 = pd.Series([10,20,30,40,50,60], dtype=float)

print(srs1[1])
print(srs1[0])
print(srs1[2], srs1[3])
print(srs1[[2,3]])
print(srs1.index, srs1.values)
srs1.astype(int)    # 자료형 변경 srs1.astype(np.float32)
print()

# 결과
20.0
10.0
30.0 40.0
2    30.0
3    40.0
dtype: float64
RangeIndex(start=0, stop=6, step=1) [10. 20. 30. 40. 50. 60.]

 

Series에 index 부여 가능

Series와 index에 각각 name 부여 가능

srs2 = pd.Series([10,20,30,40,50,60], index = ['a','b','c','d','e','f'])
print(srs2['a'])
print(srs2['c'], srs2[2])
print(srs2[['a','c']])

# index값 없을 때 부여 가능
srs2.index = ['a','b','c','d','e','f']

# Series와 index에 name 부여
srs2.name = 'Points'
srs2.index.name = 'Person'
srs2

# 결과
10
30 30
a    10
c    30
dtype: int64
Person
a    10
b    20
c    30
d    40
e    50
f    60
Name: Points, dtype: int64

 

pandas 의 date_range 함수 -> 날짜 범위 데이터를 index로 사용 가능

+, -, *, / 연산의 결과는 Series 객체

dates = pd.date_range("2020-07-27", "2020-07-31")
temp1 = pd.Series([27,31,28,39,30], index=dates)
print(temp1)
print()

temp2 = pd.Series([30,33,25,29,32], index=dates)
temp_diff = temp2 - temp1
print(temp_diff)
print(temp_diff['2020-07-31'], temp_diff[4])
print()

# 기술적 통계함수 적용 가능
print(temp1.mean())
print(min(temp1))

# 결과
2020-07-27    27
2020-07-28    31
2020-07-29    28
2020-07-30    39
2020-07-31    30
Freq: D, dtype: int64

2020-07-27     3
2020-07-28     2
2020-07-29    -3
2020-07-30   -10
2020-07-31     2
Freq: D, dtype: int64
2 2

31.0
27

 

2차원 형태 리스트를 Series로

srs3 = pd.Series([[1,2,3,4], [5,6,7,8]])
print(srs3.index)
print(srs3.values)
print(srs3[0])
print(srs3[0][0])
print(srs3[[0,1]])

# 결과
RangeIndex(start=0, stop=2, step=1)
[list([1, 2, 3, 4]) list([5, 6, 7, 8])]
[1, 2, 3, 4]
1
0    [1, 2, 3, 4]
1    [5, 6, 7, 8]
dtype: object

 

 

2. DataFrame

 

하나 이상의 Series 객체를 갖는 인덱스 레이블 당 복수의 값을 가짐

컬럼 중심의 데이터 형식

관계형데이터베이스의 테이블과 유사함

 

srs3 = pd.DataFrame([[1,2,3,4], [5,6,7,8]])
print(srs3)
print(srs3[2])
print(srs3[2][0])
print(srs3[[1,3]])

# 결과
0  1  2  3
0  1  2  3  4
1  5  6  7  8
0    3
1    7
Name: 2, dtype: int64
3
   1  3
0  2  4
1  6  8

 

1) columns, index 속성 부여

 

- column에 이름이 부여되면 기존의 컬럼이름을 사용할 수 없음

- 행의 이름인 index는 새롭게 부여되어도 인덱스 번호를 함께 사용할 수 있음

 

srs3 =pd.DataFrame([[1,2,3,4], [5,6,7,8]], columns = ['a','b','c','d'], index = ['aa', 'bb'])
print(srs3)
print(srs3['b'])
print()
print(srs3['b'][0])
print(srs3[['b','c']])

# columns, index 이름 변경 가능
srs3.index = ['cc','dd']
srs3.columns = ['one','two','three','four']
print(srs3)

# 결과
    a  b  c  d
aa  1  2  3  4
bb  5  6  7  8
aa    2
bb    6
Name: b, dtype: int64

2
    b  c
aa  2  3
bb  6  7

    one  two  three  four
cc    1    2      3     4
dd    5    6      7     8

 

2) Series를 DataFrame으로 적용하기

 

- name 속성이 필요함

- 딕셔너리형태로 name을 키 값으로 부여해주거나, 시리즈에 name 속성을 부여해 주어야 함

dates = pd.date_range('2020-07-27', '2020-07-31')

temp1 = pd.Series([27,31,28,29,30], index=dates)
temp2 = pd.Series([30,33,25,29,32], index=dates)

temp_df = pd.DataFrame({'Seoul':temp1, 'Pusan':temp2})

print(temp_df)
print(temp_df['Seoul'])
print(temp_df['Seoul']['2020-07-31'])

# 결과
             Seoul  Pusan
2020-07-27     27     30
2020-07-28     31     33
2020-07-29     28     25
2020-07-30     29     29
2020-07-31     30     32

2020-07-27    27
2020-07-28    31
2020-07-29    28
2020-07-30    29
2020-07-31    30
Freq: D, Name: Seoul, dtype: int64

30
# temp_df2 = pd.DataFrame([temp1,temp2]) : 오류
temp1.name = 'Seoul'
temp2.name = 'Pusan'
temp_df2 = pd.DataFrame([temp1,temp2])
temp_df2

# 결과
	2020-07-27	2020-07-28	2020-07-29	2020-07-30	2020-07-31
Seoul	27	31	28	29	30
Pusan	30	33	25	29	32

 

3) DataFrame의 행 단위 이용

 

- loc, iloc 사용

- loc : 인덱스 이름을 사용함

- iloc : 인덱스 번호를 사용함

temp_df2.loc['Seoul']
temp_df2.iloc[0]

# 결과
2020-07-27    27
2020-07-28    31
2020-07-29    28
2020-07-30    29
2020-07-31    30
Freq: D, Name: Seoul, dtype: int64
from IPython.display import display # IPython shell 환경에서 dataframe을 table형식으로 보여줌

df = pd.DataFrame(np.array([[1,2,3], [10,20,30], [7,8,9]]), index = [1,'B',2], columns=['T','N','P'])
display(df)

print(df.iloc[1])
print(df.loc['B'])

# 결과
	T	N	P
1	1	2	3
B	10	20	30
2	7	8	9

T    10
N    20
P    30
Name: B, dtype: int32

 

4) pd.concat

 

여러개의 배열을 합치는 함수

dates = pd.date_range('2020-07-27', '2020-07-31')

temp1 = pd.Series([27,31,28,0,30], index=dates)
temp2 = pd.Series([30,33,25,29,32], index=dates)
temp3 = pd.Series([27,25,26,0,28], index=dates, name='Kwangju')
temp4 = pd.Series([29,0,26,28,30], index=dates)

temp5 = pd.concat([temp1,temp2], axis=1, keys=['Seoul','Pusan'])
temp6 = pd.concat([temp5,temp3], axis=1)
print(temp6)
temp7 = temp5.append(temp3, ignore_index=True)
print(temp7)

# 결과
            Seoul  Pusan  Kwangju
2020-07-27     27     30       27
2020-07-28     31     33       25
2020-07-29     28     25       26
2020-07-30      0     29        0
2020-07-31     30     32       28

   Seoul  Pusan  2020-07-27 00:00:00  2020-07-28 00:00:00  \
0   27.0   30.0                  NaN                  NaN   
1   31.0   33.0                  NaN                  NaN   
2   28.0   25.0                  NaN                  NaN   
3    0.0   29.0                  NaN                  NaN   
4   30.0   32.0                  NaN                  NaN   
5    NaN    NaN                 27.0                 25.0   

   2020-07-29 00:00:00  2020-07-30 00:00:00  2020-07-31 00:00:00  
0                  NaN                  NaN                  NaN  
1                  NaN                  NaN                  NaN  
2                  NaN                  NaN                  NaN  
3                  NaN                  NaN                  NaN  
4                  NaN                  NaN                  NaN  
5                 26.0                  0.0                 28.0

 

5) join

 

- DataFrame을 합침

- merge 함수 사용

- on 속성 : 공통 속성의 컬럼을 적어줌

left = pd.DataFrame({'key':['foo','bar'], 'lval':[1,2]})
right = pd.DataFrame({'key':['foo','bar'], 'rval':[4,5]})
pd.merge(left, right, on='key')

left = pd.DataFrame({'key':['foo','foo'], 'lval':[1,2]})
right = pd.DataFrame({'key':['foo','foo'], 'rval':[4,5]})
left_right = pd.merge(left, right, on='key')
display(left_right)

# 결과
      key	 lval    rval
0	foo	   1	4
1	bar	   2	5

	 key	  lval	rval
0	foo 	   1	4
1	foo 	   1	5
2	foo	    2	4
3	foo	    2	5

 

6) 컬럼 추가

 

- loc 사용 또는 dataframe이름['새로운 컬럼 이름]

df = pd.DataFrame(np.array([[1,2,3], [10,20,30], [7,8,9]]), index=[1,'B',2], columns=['T','N','P'])
display(df)

# loc 사용
df.loc[:, 'Y'] = pd.Series([100,200,300], index=df.index)
display(df)
# dataframe이름['새로운컬럼이름']
df['M'] = pd.Series([11,12,13], index=df.index)
display(df)

# 결과
	T	N	P
1	1	2	3
B	10	20	30
2	7	8	9

       T	N	P	Y
1	1	2	3	100
B	10	20	30	200
2	7	8	9	300

       T	N	P	Y	M
1	1	2	3	100	11
B	10	20	30	200	12
2	7	8	9	300	13

 

 

7) 컬럼 삭제

 

- drop 함수 사용

- inplace = True : 변화 내용을 원본에 반영함

a = df.drop('T', axis=1, inplace=False)
display(df)
display(a)
df.drop('T', axis=1, inplace=True)
display(df)

# 결과
       T	N	P	Y	M
1	1	2	3	100	11
B	10	20	30	200	12
2	7	8	9	300	13

       N	P	Y	M
1	2	3	100	11
B	20	30	200	12
2	8	9	300	13

       N	P	Y	M
1	2	3	100	11
B	20	30	200	12
2	8	9	300	13

 

8) row 삭제

 

- index와 drop 명령어 사용

print(df.index[1])
df.drop(df.index[1], inplace=True)
print(df)
print(df.drop(1))
display(df)

# 결과
B

   N  P    Y   M
1  2  3  100  11
2  8  9  300  13
   N  P    Y   M
2  8  9  300  13

       N	P	Y	M
1	2	3	100	11
2	8	9	300	13

 

9) 데이터 수정

df.iloc[0,0] = 1000
display(df)
df.loc[1,'N'] = 2000
display(df)

x = pd.DataFrame({'x':[1,2,3], 'y':[3,4,5]})
x.iloc[1] = {'x':9, 'y':99}
x

# 결과
	N	    P	Y	M
1	1000	    3	100	11
2	8	    9	300	13

       N	   P	Y	M
1	2000	   3	100	11
2	8	   9	300	13

       x	y
0	1	3
1	9	99
2	3	5

 

10) DataFrame 복합읽기

import matplotlib.pyplot as plt

temp6.loc['2020-07-27':'2020-07-29','Seoul':'Pusan']
temp6.loc[temp6['Seoul']>30,:]
temp6.loc[temp6['Seoul']>30, 'Seoul':'Seoul']
temp6.loc[temp6['Pusan']>30]
temp6[temp6['Pusan']>30]

print(temp6.Pusan[0:3])
print(temp6.Pusan[temp6.Pusan>30])
print(temp6[temp6.Seoul>30])
print(temp6.Pusan['2020-07-27':'2020-07-29'])

print(temp6.iloc[[1,3]].Seoul)
print(temp6.Kwangju>27)

temp6.Seoul.plot()
temp6.plot()
plt.show()

# 결과
2020-07-27    30
2020-07-28    33
2020-07-29    25
Freq: D, Name: Pusan, dtype: int64
2020-07-28    33
2020-07-31    32
Name: Pusan, dtype: int64
            Seoul  Pusan  Kwangju
2020-07-28     31     33       25
2020-07-27    30
2020-07-28    33
2020-07-29    25
Freq: D, Name: Pusan, dtype: int64
2020-07-28    31
2020-07-30     0
Freq: 2D, Name: Seoul, dtype: int64
2020-07-27    False
2020-07-28    False
2020-07-29    False
2020-07-30    False
2020-07-31     True
Freq: D, Name: Kwangju, dtype: bool

 

 

'Programming > Python' 카테고리의 다른 글

Python 8주차 - 2  (0) 2020.08.10
Python 8주차 - 1  (0) 2020.08.05
Python 7주차 - 1  (0) 2020.07.29
Python 6주차 - 2  (0) 2020.07.26
Python 6주차 - 1  (0) 2020.07.26
Comments