Showing posts with label P-basics. Show all posts
Showing posts with label P-basics. Show all posts

Jun 24, 2025

[Python] module vs package

* Module(모듈): .py 파일 하나 (책 한권)

  - ex: math.py, os.py

* Package(패키지): __init__.py가 있는 폴더

  - 여러 모듈을 포함한 폴더 (책장이 있는 책꽂이)

  - __init__.py 파일이 있어야 패키지로 인식됨

  - numpy, sklearn, ...



Mar 7, 2023

[Python] pandas.DataFrame 활용 (Usage pandas.DataFrame)


# reference: https://pandas.pydata.org/docs/user_guide/10min.html

import pandas as pd

# Loading data
df_LH_apt = pd.read_csv("C:\\Users\\user\\Desktop\\sw_data\\LH_apt_20220722.csv", encoding='CP949') # ./: current working directory
df_LH_apt
Output

# Viewing data from 0 row to 5 row
df_LH_apt.head()
Output

# Viewing data from n-4 to n row, n: last index
df_LH_apt.tail()
Output

# Total index
df_LH_apt.index

# Total columns
df_LH_apt.columns


# Total data types
df_LH_apt.dtypes
Output

# Choosing number style column
df_LH_apt.select_dtypes(include = "number")
Output

# Choosing object style column
df_LH_apt.select_dtypes(include = "object")

# Select "세대수" column
df_LH_apt["세대수"] # or df_LH_apt.세대수
df_LH_apt[["세대수", "동수", "주소"]] # multi-column

df_LH_apt_piece = df_LH_apt.copy()[10:18]
df_LH_apt_piece
Output


# DataFrame에 할당된 index 기준
df_LH_apt_piece.loc[10, :]
Output

# DataFrame에 있는 순서 기준, 내부 index는 slicing 문법 적용
df_LH_apt_piece.iloc[0, :]
Output

# 데이터 접근, row에 slicing, column에 특정 변수
df_LH_apt.loc[4:8, ["세대수", "준공일"]] # or df_LH_apt[4:8][["세대수", "준공일"]]
# 데이터 접근, row과 column에 slicing
df_LH_apt.loc[4:8, '세대수' : '준공일']
# 데이터 접근, 모든 row
df_LH_apt.loc[:, '세대수' : '준공일']
# 데이터 접근, row에 slicing, 모든 column
df_LH_apt.loc[4:8, :]

# '단지'로 시작하는 columnes
df_LH_apt.filter(regex='^단지')
Output

# 내부 조건에 해당하는 데이터 선택
df_LH_apt[df_LH_apt["세대수"] > 1500]

# 여러개의 내부 조건이 있는 경우, 즉, & or | 조건에 해당하는 데이터 선택
df_LH_apt[(df_LH_apt["세대수"] > 1500) & (df_LH_apt["동수"] < 30)]
df_LH_apt[(df_LH_apt["세대수"] > 1500) | (df_LH_apt["동수"] < 30)]

# 해당 column에 있는 값 유형 확인
df_LH_apt["주택유형"].unique()
Output

# 해당 column에 특정 값 유형 있는 데이터를 산출
df_LH_apt[df_LH_apt["주택유형"].isin(["공공임대(10년)", "임대상가"])]

# 해당 column 기준 가장 큰 값 5개, 같은 값을 때 모두 포함해서 표시
df_LH_apt.nlargest(5, "동수", keep= "all")

# 해당 column 기준 가장 작은 값 5개, 같은 값을 때 모두 포함해서 표시
df_LH_apt.nsmallest(5, "동수", keep= "all")

# 해당 column값에 따른 오름차순 정렬, default가 오름차순
df_LH_apt.sort_values("세대수") # or df_LH_apt.sort_values("세대수", ascending = True)
# 해당 column값에 따른 내림차순 정렬
df_LH_apt.sort_values("세대수", ascending = False)
# 여러 column을 기준으로도 정렬 가능
df_LH_apt.sort_values(["세대수", "동수"], ascending = [False, False])

# index 기준 재정렬
df_LH_apt.sort_index()

Jan 20, 2023

파이썬-text 파일 쓰기, 읽기, 추가하기 (.txt writing, reading, and adding in Python)

■ .txt 파일 생성 후 쓰기

※ 한글 사용 시, utf-8로 encoding을 지정해 준다.

f = open("text_file.txt", "w", encoding="utf-8")
for i in range(1, 5):
    text_line = "{0}번째 줄입니다. \n" .format(i)
    f.write(text_line)

f.close()

Output in "text_file.txt"
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 출력하기

- readline() 함수 사용, while 문으로 한 줄 한 줄, 읽은 것을 출력

f = open("text_file.txt", "r", encoding="utf-8")

while True:
    line = f.readline()
    if not line:    
        break

    print(line)

f.close()

Output
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 출력하기 II

- readlines() 함수 사용, 전체 읽어서 한 줄, 한줄 for문으로 출력

f = open("text_file.txt", "r", encoding="utf-8")

lines = f.readlines()
for line in lines:
    print(line)

f.close()

Output
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 출력하기 III

- read() 함수 사용, 전체 읽어서 전체 출력

f = open("text_file.txt", "r", encoding="utf-8")
print(f.read())

Output
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 추가하기


Jan 15, 2023

Python 함수 만들기 (functions)

 ■ No argument, No retrun (인자가 없고, 리턴이 없는 경우)

def hello_function():
    print("Hello, world!")

hello_function()

Output
Hello, world!

 ■ Yes argument, No retrun (인자가 있고, 리턴이 없는 경우)

def hello_function(name):
    print("Hello, it's me. {0}!" .format(name))

hello_function("Swan")

Output
Hello, it's me. Swan!

 ■ Yes argument, Yes retrun (인자가 있고, 리턴이 있는 경우)

def multiply_five(number):
    return number*5

multiply_five(5)

Output
25

Jan 14, 2023

파이썬을 활용한 로또 번호 추출 (Extraction of 'Lotto number' in Python)

 ■ Code & Output

- random module을 활용한 예제

import random

print("몇 장의 로또를 구매하실 건가요?")
print("숫자를 입력하세요.")
num_set =int(input("숫자를 입력하세요: "))
print("{0}장을 구매했습니다." .format(num_set))

for i in range(1, num_set+1):
    lotto_numbers = random.sample(range(1, 46), 6)
    lotto_numbers.sort()

    print("{0}장, {1}" .format(i, lotto_numbers))

print("1등을 기원합니다.")

Output
몇 장의 로또를 구매하실 건가요? 숫자를 입력하세요. 3장을 구매했습니다. 1장, [1, 9, 25, 27, 36, 45] 2장, [12, 18, 22, 27, 29, 39] 3장, [11, 17, 19, 36, 37, 41] 1등을 기원합니다.

파이썬을 활용한 오늘 메뉴 선택 프로그램 (Choosing a today's memu in Python)

import random
options = ["치킨", "김밥", "국밥", "돈가스", "제육덮밥", "김치찌개", "떡국"]

def today_menu():
    menu = random.choice(options)
    return menu

today_choice_menu = today_menu()
print("오늘 점식 메뉴는 {0} 입니다." .format(today_choice_menu))

Output
오늘 점식 메뉴는 떡국 입니다.

Jan 2, 2023

파이썬으로 2중 반복문을 활용한 구구단 및 문자열 formatting 종류 (Multiplication table using a double for-loop in Python)

print("구구단 2단부터 9단까지 시작!")

for i in range(2, 10, 1):
    for j in range(1, 10, 1):
        print(i, "x", j, "=", i*j)                   # case1
        print("%d x %d = %d"  % (i, j, i*j))         # case2
        print(f'{i} x {j} = {i*j}')                  # case3
        print("{0} x {1} = {2}".format(i, j, i*j))   # case4

Output exceeds the size limit. Open the full output data in a text editor
구구단 2단부터 9단까지 시작! 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27

Jan 1, 2023

List Comprehension example in Python

 ■ Before comprehension

words = ["apple", "bus", "camera", "dog", "eye", "five", "game"]

new_list = []

for x in words:
    if "e" in x:
        new_list.append(x)

print(new_list)

Output
['apple', 'camera', 'eye', 'five', 'game']

 ■ After comprehension

words = ["apple", "bus", "camera", "dog", "eye", "five", "game"]
new_list = [x for x in words if "e" in x]

print(new_list)

['apple', 'camera', 'eye', 'five', 'game']

파이썬 반복문 (for문), range(..., ..., ...,) example

■ 문자로 for문

for x in "abcdef":
    print(x)

Output
a b c d e f

■ List로 for문

words = ["apple", "bus", "camera", "dog", "eye", "five", "game"]

for x in words:
    print(x)

Output
apple bus camera dog eye five game

■ for문 range 활용 I

for i in range(6):
    print(i)

Output
0 1 2 3 4 5

■ for문 range 활용 II

for i in range(1, 6):
    print(i)

Output
1 2 3 4 5

■ for문 range 활용 III

for i in range(0, 8, 2):
    print(i)

Output
0 2 4 6

■ for문 range 활용 IV

for i in range(100, 50, -10):
    print(i)

Output
100 90 80 70 60


Dec 3, 2022

Markdown Guide in Python

Address: Markdown Guide

■ Heading Size

Markdown Syntax

# H1: Big
## H2: Middle
### H3: Small
#### H4: SSmall
##### H5: SSSmall
###### H6: SSSSmall

Normal text

Output


May 24, 2021

[Python] Atithmetic operators, data type, relational and comparison operators, print, format string, input (파이썬: 산술 연산자, 데이터자료형, 관계 및 비교 연산자, 출력, 입력)

■ Atithmetic operators (산술 연산자)

[Input]

print(1 + 1)

print(1 - 1)

print(2 * 2) # 곱셈

print(4 / 3) # 나눗셈->실수

print(4 // 3) # 몫만 계산

print(4 % 3) # 나머지만 계산

print(2 ** 10) #승수 연산자

[Output]

2 0 4 1.3333333333333333 1 1 1024

■ Data type (데이터 자료형)

[Input]

print(type(3))

print(type('A'))

print(type(3.14))

[Output]
<class 'int'> <class 'str'> <class 'float'>

■ Relational and comparison operators (관계 및 비교 연산자)

[Input]
print(10 < 3)
print(10 >3)
print(10 >= 3)
print(10 <= 3)
print(10 == 3)
print(10 != 3)
[Output]
False
True True False False True

May 1, 2021

[Python] 공공데이터를 가져올 수 있는 유용한 사이 (A a useful site for gathering public data)

1. 공공데이터 포털
https://www.data.go.kr/index.do

2. 서울 열린데이터 광장
https://data.seoul.go.kr/index.do

3. DACON
https://dacon.io/