GO WILD, SPEAK LOUD, THINK HARD

엘리스 AI 트랙 12주차 - 파이썬 실전 데이터 분석 I (3/19) 🔥 본문

개발/엘리스 AI 트랙

엘리스 AI 트랙 12주차 - 파이썬 실전 데이터 분석 I (3/19) 🔥

Max 2021. 3. 29. 09:38
반응형

✔ 12주차. 데이터 분석 핵심 기법

<학습 목표>

  1. 파이썬 라이브러리인 Pandas, Numpy, Matplotlib의 사용할 수 있습니다.
  2. 파이썬 라이브러리를 활용하여 데이터 분석을 할 수 있습니다.
  3. 데이터를 분석하고 시각화하는 방법을 알수 있습니다.

[01 트럼프 대통령 트윗으로 시작하는 데이터 처리]

1. 리스트 순회하기
  - for 반복문

# 기본 for문
for num in range(10):
    print(num)  # 0, 1, 2, ... 9

# 리스트 순회하기
fruits = ["사과", "바나나", "키위"] 
for i in range(len(fruits)): 
    print("과일" + str(i+1) + ": fruits[i]") # 과일 1 사과 ...

  - 문장의 단어를 하나씩 가져오기 : for 반복문과 in 키워드를 이용해 리스트의 원소를 하나씩 가져와 변수에 저장함. 리스트의 길이를 구하는 len()와 연속된 정수를 만들어주는 range() 함수를 함께 사용하면 원소의 인덱스를 가져올 수 있다.

trump_tweets = [
  'Will be leaving Florida for Washington (D.C.) today at 4:00 P.M. Much work to be done, but it will be a great New Year!',
  'Companies are giving big bonuses to their workers because of the Tax Cut Bill. Really great!',
  'MAKE AMERICA GREAT AGAIN!'
]

def date_tweet(tweet):
    for index in range(len(tweet)):
        print('2018년 1월 ' + str(index+1) + '일: ' + tweet[index])

date_tweet(trump_tweets)
# 2018년 1월 1일: Will be leaving Florida for Washington (D.C.) today at 4:00 P.M. Much work to be done, but it will be a great New Year!
# 2018년 1월 2일: Companies are giving big bonuses to their workers because of the Tax Cut Bill. Really great!
# 2018년 1월 3일: MAKE AMERICA GREAT AGAIN!

2. 문자열 인덱싱
  - 인덱싱 & 문자열 인덱싱

# 리스트 인덱싱
fruits = ["사과", "바나나", "키위", "배"] 

print(fruits[-1])  # 배
print(fruits[1:3]) # 바나나, 키위
print(fruits[1:])  # 바나나, 키위, 배
print(fruits[:3])  # 사과, 바나나, 키위

# 문자열 인덱싱
word = "superman" 
print(word[3])  # 'e' 
print(word[-2]) # 'a' 
print(word[5:]) # 'man' 
print(word[:5]) # 'super'

  - 단어의 일부분 가져오기

trump_tweets = ['thank', 'you', 'to', 'president', 'moon', 'of', 'south', 'korea', 'for', 'the',
               'beautiful', 'welcoming', 'ceremony', 'it', 'will', 'always', 'be', 'remembered']

def print_korea(text):
    for word in text:
        if word[0] == "k":
            print(word)

print_korea(trump_tweets) # korea

3. 문자열 함수
  ① startswith() : 요소로 시작하는지 확인하는 함수

word = "superman" 
print(word.startswith('s')) # True

if word.startswith('a'): 
    print("a로 시작하는 단어입니다.")

  - 단어의 첫 글자 확인하기

trump_tweets = ['thank', 'you', 'to', 'president', 'moon', 'of', 'south', 'korea', 'for', 'the',
               'beautiful', 'welcoming', 'ceremony', 'it', 'will', 'always', 'be', 'remembered']

def print_korea(tweet):
    for word in tweet:
        if word.startswith("k"):
            print(word)
    
print_korea(trump_tweets) # korea

  ② .split() : 특정 문자를 기준으로 문자열을 나눌때 사용. 기본값 공백. (대표적인 공백문자 : 빈칸(' '), Tab('\t'), Newline('\n')

intro = "제 이름은 엘리스입니다." 
print(intro.split())  # ["제", "이름은", "엘리스입니다."] 

fruits = "사과,귤,배,바나나" 
print(fruits.split(','))  # ["사과", "귤", "배", "바나나"]

numbers = "  1 2 3  "
print(numbers.split())    # ['1', '2', '3'] 
print(numbers.split(' ')) # ['', '', '1', '', '2', '', '3', '', '']

  - 문장을 단어 단위로 구분하기

trump_tweets = "thank you to president moon of south korea for the beautiful welcoming ceremony it will always be remembered"

def break_into_words(text):
    return text.split()

print(break_into_words(trump_tweets))
# ['thank', 'you', 'to', 'president', 'moon', 'of', 'south', 'korea', 'for', 'the', 
# 'beautiful', 'welcoming', 'ceremony', 'it', 'will', 'always', 'be', 'remembered']

  ③ .append() : 리스트 마지막에 새로운 요소를 추가. 리스트를 직접 수정함.

numbers = [] 
numbers.append(1) 
print(numbers)  # [1] 
numbers.append(2) 
print(numbers)  # [1, 2]

numbers = [1, 2, 10, 17] 
small_numbers = [] 
for num in numbers: 
    if number < 10: 
        small_numbers.append(num)

print(small_numbers)  # [1, 2]

  - 새로운 단어 추가하기

trump_tweets = ['america', 'is', 'back', 'and', 'we', 'are', 'coming', 'back', 'bigger', 'and',
                'better', 'and', 'stronger', 'than', 'ever', 'before']

def make_new_list(text):
    new_list = []
    for i in text:
        if i.startswith("b"):
            new_list.append(i)
   
    return new_list

print(make_new_list(trump_tweets))  # ['back', 'back', 'bigger', 'better', 'before']

  ④ lower() : 소문자로 변환 / upper() : 대문자로 변환 → 두 함수 모두 리스트를 직접 수정하지X, 변수에 저장해서 사용해야 함.

intro = "My name is Elice!" 
print(intro.upper())  # "MY NAME IS ELICE!" 
print(intro.lower())  # "my name is elice!"

  - 대소문자 변환하기

trump_tweets = [
    "FAKE NEWS - A TOTAL POLITICAL WITCH HUNT!",
    "Any negative polls are fake news, just like the CNN, ABC, NBC polls in the election.",
    "The Fake News media is officially out of control.",
]
 
def lowercase_all_characters(text):
    processed_text = []
    for i in text:
        processed_text.append(i.lower())
    
    return processed_text

print('\n'.join(lowercase_all_characters(trump_tweets)))
# fake news - a total political witch hunt!
# any negative polls are fake news, just like the cnn, abc, nbc polls in the election.
# the fake news media is officially out of control.

  ⑤ .replace(변경할 문자열, 대체 문자열) : 문자열에서 특정 문자나 문자열을 다른 문자(열)로 변경할 때 사용.

intro = "제 이름은 Elice입니다." 

print(intro.replace('Elice', '엘리스')) # 제 이름은 엘리스입니다.
print(intro.replace(' ', ''))   # 제이름은Elice입니다.

intro.replace(' ', '')  
print(intro)  # 제 이름은 Elice입니다. => 변환된 값을 저장하지 않았기 때문에 처음 값과 같음

  - 특수기호 삭제하기

trump_tweets = [
    "i hope everyone is having a great christmas, then tomorrow it’s back to work in order to make america great again.",
    "7 of 10 americans prefer 'merry christmas' over 'happy holidays'.",
    "merry christmas!!!",
]

def remove_special_characters(text):
    processed_text = []
    for i in text:
        processed_text.append(i.replace(',', '').replace("'", '').replace('!', ''))
    
    return processed_text

print('\n'.join(remove_special_characters(trump_tweets)))
# i hope everyone is having a great christmas then tomorrow it’s back to work in order to make america great again.
# 7 of 10 americans prefer merry christmas over happy holidays.
# merry christmas

4. 트럼프 대통령 트윗 분석하기
  ① preprocess_text(text)
    - 문자열 text를 가공후 반환 : 모든 알파벳 대문자 → 알파벳 소문자로 변경, 특수문자 삭제, 공백으로 나눠 리스트 형태로 반환
  ② analyze_text(words)
    - words 리스트의 각각의 원소는 모두 keywords 리스트에 저장, @나 #로 시작한다면 첫 번째 글자는 제거하고 저장
    - #로 시작하는 원소는 hashtags 리스트, @로 시작하는 원소는 mentions 리스트에 첫 번째 문자(#, @) 제거후 저장
    - keywords(모든 키워드), hashtags(해쉬태그 키워드), mentions (멘션 키워드) 반환
  ③ filter_by_month(tweet_data, month)
    - 트윗 데이터와 트윗이 작성된 월(정수)을 입력 받아 해당 월에 게시된 트윗을 리스트에 저장 후 반환

import numpy as np
from collections import Counter
from string import punctuation

# 1번
def preprocess_text(text):
    text = text.lower()
    symbols = punctuation.replace('@', '').replace('#', '')
    
    for i in symbols:
        text = text.replace(i, '')
        
    text = text.split()  
    return text
    

# 2번
def analyze_text(words):
    keywords, hashtags, mentions = [], [], []
    
    for i in words:   
        if i[0] == "@":
            mentions.append(i.replace('@', ''))
            keywords.append(i.replace('@', ''))
        elif i[0] == "#":
            hashtags.append(i.replace('#', ''))
            keywords.append(i.replace('#', ''))
        else:
            keywords.append(i)
    
    return keywords, hashtags, mentions

# 3번
def filter_by_month(tweet_data, month):
    month_string = '0' + str(month) if month < 10 else str(month)

    filtered_tweets = []
    for i in tweet_data:
        
        if i[0][:2] == month_string:
            filtered_tweets.append(i[1])
    
    return filtered_tweets

[02 영어 단어 모음으로 시작하는 텍스트 파일 분석]

1. 파일 다루기
  - open() : 파일 열기 / close() : 닫기
  - with open as blahblah : 파일 자동으로 닫기

# 파일 열기/닫기
file = open('data.txt')
content = file.read() 
file.close()

# 파일 자동으로 닫기
with open('data.txt') as file: 
    content = file.read() 

# 줄 단위로 읽기
contents = [] 
with open('data.txt') as file: 
    for line in file: 
        contents.append(line)

# 파일의 모드
with open('data.txt', 'w') as file: # w : 쓰기모드 / r : 읽기모드
    file.write('Hello')

2. 데이터 구조 다루기
  - 튜플 : Tuple. 소괄호 사용. 리스트와 비슷함(인덱스 등등). 값을 바꾸려면 새로운 튜플을 만들어야 함.
  - 튜플과 리스트의 차이

 

튜플

리스트

공통점

순서가 있는 원소들의 집합

차이점

원소값 수정 X

원소갯수 변경 X

원소값 수정 O

원소갯수 변경 O

  - 데이터 형태 변환하기

filename = 'corpus.txt'

def import_as_tuple(filename):
    tuples = []
    with open(filename) as file:
        for line in file:
            line = line.replace("\n", '').split(",")
            tuples.append((line[0], line[1]))
            
    return tuples

3. 리스트로 리스트 만들기
  - List Comprehension

# 기존 방식
words = ['Make', 'Me', 'Happy']
first_letters = []
for word in words:
    first_letters.append(word[0])
    
# List Comprehension
words = ['Make', 'Me', 'Happy']
first_letters = [word[0] for word in words]


# 기존방식
numbers = [1, 2, 3, 4]
even = []
for n in numbers:
    if n % 2 == 0:
        even.append(n)

# List Comprehension
numbers = [1, 2, 3, 4]
even = [n for n in numbers if n % 2 == 0]

  - 한 줄 명령어로 데이터 다루기

words = ['apple', 'banana', 'alpha', 'bravo', 'cherry', 'charlie' ]

def filter_by_prefix(words, prefix):
    return [i for i in words if i.startswith(prefix)]

a_words = filter_by_prefix(words, 'a')
print(a_words) # ['apple', 'alpha']

4. 데이터 정렬하기
  - sorted : 리스트를 정렬하는 기본 함수. key 인자로 여러가지 사용 가능(절댓값, 함수 등등)

# 절댓값으로 정렬
num = [-9, 3, -100, 4, 5, 40, 23, 1000]
sort_by_abs = sorted(num, key = abs) # [3, 4, 5, -9, 23, 40, -100, 1000]

# 문자열 정렬
fruits = ['cherry', 'apple', 'banana']
sort_by_alphabet = sorted(fruits) # ['apple', 'banana', 'cherry']

# key 인자로 함수 사용
def reverse(word):
	return str(reversed(word))
    
sort_by_last = sorted(fruits, key=reverse) # ['cherry', 'apple', 'banana']

  - 데이터 정렬하기

pairs = [('time', 8), ('the', 15), ('turbo', 1)]

def get_freq(pair):
    return pair[1]

def sort_by_frequency(pairs):
    return sorted(pairs, key=get_freq)

print(sort_by_frequency(pairs)) # [('turbo', 1), ('time', 8), ('the', 15)]

5. 그래프 다루기
  - matplotlib : Mathematical Plot Library. 파이썬에서 그래프를 그릴 수 있게 하는 라이브러리. (꺾은선 그래프, 막대 그래프등 지원)
  - 차트 그리기

# matplotlib import
import matplotlib.pyplot as plt

years = [2013, 2014, 2015, 2016, 2017]
temperatures = [5, 10, 15, 20, 17]

def draw_graph():
    # 막대 그래프의 막대 위치를 결정
    pos = range(len(years))  # [0, 1, 2, 3, 4]
    
    # 높이가 온도인 막대 그래프를 그리고 가운데 정렬
    plt.bar(pos, temperatures, align='center')
    
    # 연도 표기
    plt.xticks(pos, years)
    
    # 그래프 저장
    plt.savefig('graph.png')

draw_graph()

6. 영어 단어 모음 분석하기
  - import_corpus(filename) : 단어와 빈도수 데이터가 담긴 파일 한 개를 불러온 후, (단어, 빈도수) 꼴의 튜플로 구성된 리스트를 반환
  - create_corpus(filenames) : 텍스트 파일 여러 개를 한 번에 불러온 후, (단어, 빈도수) 꼴의 튜플로 구성된 리스트를 반환
  - filter_by_prefix(corpus, prefix) : (단어, 빈도수) 꼴의 튜플들을 담고 있는 리스트의 형태로 주어지는 corpus의 데이터 중 특정 문자열 prefix로 시작하는 단어 데이터만 추린 리스트를 반환
  - most_frequent_words(corpus, number) : corpus의 데이터 중 가장 빈도가 높은 number개의 데이터만 추려서 반환

from collections import Counter
from string import punctuation

def import_corpus(filename):
    corpus = []
    
    with open(filename) as file:
        # 파일을 읽어서 각 줄을 (단어, 빈도수) 튜플로 저장
        for line in file:
            line = line.replace('\n', "").split(",")
            corpus.append((line[0], int(line[1])))
    
    # print(corpus)
    return corpus

def create_corpus(filenames):
    words = []
    
    # 여러개의 파일리스트를 for문을 통해 읽음
    for filename in filenames:
        with open(filename) as file:
            content = file.read()
            # punctuation으로 문장부호를 포함한 모든 특수기호를 제거
            for symbol in punctuation:
                content = content.replace(symbol, "")
            words = words + content.split()
    
    # counter 사용해 words 단어와 빈도수 형태로 변경
    corpus = Counter(words)
    # print(corpus)
    return list(corpus.items())

def filter_by_prefix(corpus, prefix):
    # prefix로 시작하는 단어 찾아서 리턴
    return [n for n in corpus if n[0].startswith(prefix)]

def most_frequent_words(corpus, number):
    # 가장 빈도수가 높은 단어 number 개만 찾아서 리턴
    corpus = sorted(corpus, key = lambda x : x[1], reverse=True)
    # print(corpus)
    return corpus[:number]

※ 수업 자료의 출처는 K-Digital Training x 엘리스 인공지능 서비스 개발 기획 1기 (elice.io/)입니다.

반응형
Comments