리스트 자료형보다 데이터를 체계적으로 잘 정리해서 저장을 합니다. 정리가 잘되어있으니까 데이터 검색을 빠르게 할 수 있습니다.
2. 딕셔너리 자료형으로 테이블이 가능
오라클의 테이블이 파이썬과 R 에서는 data frame 이라고 합니다. 판다스 데이터프레임으로 만들어놓기만 하면 너무 쉽게 검색되고 너무 쉽게 시각화 할 수 있습니다.
예제1.
a = { '마이클 잭슨' : '하루 6시간씩 꾸준히 춤 연습을 했어요.',
'김연아' : '공중 세바퀴 회전 1번 실패하면 65번씩 연습했어요.',
'박태환' : '하루에 15,000km 이상 수영해야 세계적인 선수들과 겨룰 수 있어요' }
a['김연아']
예제2. a 딕셔너리에서 key 값들만 출력하시오.
예제3. a 딕셔너리에서 values 값들만 출력하시오.
예제4. a 딕셔너리에서 key와 values 값을 동시에 출력하시오.
예제5. a 딕셔너리에 새로운 데이터(키와 값)을 추가하시오
a = { '마이클 잭슨' : '하루 6시간씩 꾸준히 춤 연습을 했어요.',
'김연아' : '공중 세바퀴 회전 1번 실패하면 65번씩 연습했어요.',
'박태환' : '하루에 15,000km 이상 수영해야 세계적인 선수들과 겨룰 수 있어요' }
a['신유빈'] = '내가 늘 하던던데로 하면 긴장이 안되요'
a
문제1. a 딕셔너리에 안산선수 명언을 입력하시오.
a = { '마이클 잭슨' : '하루 6시간씩 꾸준히 춤 연습을 했어요.',
'김연아' : '공중 세바퀴 회전 1번 실패하면 65번씩 연습했어요.',
'박태환' : '하루에 15,000km 이상 수영해야 세계적인 선수들과 겨룰 수 있어요' }
a['안산'] = '쫄지말고 그냥쏴'
a
artist = ['비틀즈', '비틀즈', '아이유', '아이유', '마이클 잭슨', '마이클 잭슨' ]
music = ['yesterday', 'imagine', '너랑나', '마슈멜로우', 'beat it', 'smoth ciriminal' ]
music_dict = {'비틀즈':[], '아이유':[],'마이클 잭슨':[]}
for i, j in zip( artist, music ):
music_dict[i].append(j)
print( music_dict )
문제1. 아래의 감독리스트와 영화 리스트를 가지고 movie dict를 생성하시오
# 감독 리스트
directors = ['크리스토퍼 놀란', '크리스토퍼 놀란', '스티븐 스필버그', '스티븐 스필버그', '마틴 스콜세지', '마틴 스콜세지']
# 영화 리스트
movies = ['인셉션', '다크 나이트', '쥬라기 공원', 'ET', '아이리시맨', '위대한 개츠비']
movie_dict = {'크리스토퍼 놀란':[], '스티븐 스필버그':[],'마틴 스콜세지':[]}
for i, j in zip( directors, movies ):
movie_dict[i].append(j)
print( movie_dict )
※ 딕셔너리로 데이터를 구성하면 테이블을 생성하기가 쉽습니다.
테이블 즉 데이터 프레임으로 구성되기만 하면 검색이나 시각화가 정말 쉽습니다.
예제1. 겨울왕국 대본에 엘사의 대사들만 가져와서 데이터 프레임을 구성하시오.
# 엘사의 임의 대사 30개 생성 (처음에 평온한 긍정, 중간에 부정, 마지막에 큰 폭으로 긍정)
elsa_lines = [
"Elsa: It's a beautiful morning in Arendelle.",
"Elsa: The day feels promising and peaceful.",
"Elsa: Everything is serene and tranquil.",
"Elsa: I feel content and relaxed today.",
"Elsa: The air is fresh and soothing.",
"Elsa: I enjoy the calm atmosphere.",
"Elsa: My heart is light and happy.",
"Elsa: It's nice to have a quiet moment.",
"Elsa: Life is good and simple right now.",
"Elsa: I'm grateful for this peaceful time.",
"Elsa: I sense something unsettling in the air.",
"Elsa: There's a growing tension around me.",
"Elsa: I feel uncertain and uneasy.",
"Elsa: The situation is getting complicated.",
"Elsa: Problems seem to be arising everywhere.",
"Elsa: I feel overwhelmed and stressed.",
"Elsa: There is a storm brewing inside me.",
"Elsa: Everything is falling apart.",
"Elsa: I am lost and confused.",
"Elsa: This is a dark and challenging time.",
"Elsa: I must find a way through this.",
"Elsa: I can see a light at the end of the tunnel.",
"Elsa: Solutions are beginning to appear.",
"Elsa: Hope is coming back into my life.",
"Elsa: I am regaining my strength and confidence.",
"Elsa: Things are turning around for the better.",
"Elsa: I am ready to face challenges head-on.",
"Elsa: The sun is shining brighter in my heart.",
"Elsa: I believe in a positive future.",
"Elsa: Everything is possible with love and courage!"
]
# 데이터 프레임 생성
import pandas as pd
data = {"conversation" : elsa_lines } #데이터 딕셔너리 구성
df = pd.DataFrame(data)
df
※ 비 정형화된 데이터 분석하는 현업 사례 1. 빈도수 높은 단어 추출 2. 감정분석 3. 유사도 분석
예제2. 텍스트 마이닝을 쉽게 할 수 있게 해주는 패키지를 임폴트 합니다.
!pip install textblob
from textblob import TextBlob
엘사의 감정 변화가 어떻게 되는지 확인하려면 textblob 을 이용하면 긍정적인 감정이면 양수값을 출력하고 부정적인 감정이면 음수값을 출력합니다.
중간복습: 파이썬에서 사용하는 자료형 3가지 ?
1. 리스트 : 대괄호 [ ] 2. 딕셔너리 : 중괄호 { } ---> 데이터 프레임 형태의 데이터를 구성할 때 아주 유 3. 튜플 : 소괄호 ( )
예제3. 아래의 3개의 글을 데이터 프레임으로 만드시오 !
import pandas as pd
from textblob import TextBlob
# 대화 내용 리스트
elsa_lines = [
"The cold never bothered me anyway.",
"Let it go, let it go!",
"I'm happily flying with the wind and the beautiful sky."
]
# 데이터프레임 생성
data = {'conversation': elsa_lines} # 값이 리스트인 딕셔너리 자료형
df = pd.DataFrame(data) # 판다스 데이터 프레임을 구성
df
예제4. 감정 분석을 위한 함수를 생성하시오
import pandas as pd
from textblob import TextBlob
def analyze_sentiment(text):
blob = TextBlob(text) # TextBlob 객체를 생성
score = blob.sentiment.polarity # 감정 점수 계산
return sentiment_score
예제5. 아래의 3개의 글을 감정 분석하시오 !
import pandas as pd
from textblob import TextBlob
# 대화 내용 리스트
elsa_lines = [
"The cold never bothered me anyway.",
"Let it go, let it go!",
"I'm happily flying with the wind and the beautiful sky."
]
# 데이터프레임 생성
data = {'conversation': elsa_lines} # 값이 리스트인 딕셔너리 자료형
df = pd.DataFrame(data) # 판다스 데이터 프레임을 구성
# 감정분석 함수 생성
def analyze_sentiment(text):
blob = TextBlob(text) # TextBlob 객체를 생성
score = blob.sentiment.polarity # 감정 점수 계산
return score
# 감정 분석 점수 컬럼 추가 ( 엘사의 대사를 analyze_sentiment 에 입력해서 점수계산)
df['sentiment'] = df['conversation'].map(analyze_sentiment)
print( df )
문제1. lg전자 관련한 해외반응의 게시글들을 가지고 감정 점수를 위와 같이 출력하시오.
import pandas as pd
from textblob import TextBlob
# 대화 내용 리스트
lg_reviews = [
"I initially disliked my LG refrigerator because it made annoying noises, but after a quick service call, it now runs silently and keeps everything perfectly fresh.",
"I was frustrated with the delayed delivery of my LG washing machine, but its performance blew me away. It cleans clothes like no other and is incredibly efficient!",
"At first, I regretted buying the LG OLED TV due to the steep price, but the stunning picture quality and immersive experience made it worth every penny.",
"I had trouble connecting my LG soundbar to my TV initially, but once I figured it out, the sound quality was incredible and completely transformed my home theater setup.",
"The LG dishwasher left spots on my dishes initially, but after adjusting the settings, it now leaves everything sparkling clean and I couldn't be happier.",
"I thought my LG microwave was too complicated to use at first, but after reading the manual, I found it to be extremely versatile and efficient for all my cooking needs.",
"The LG smartphone battery drained quickly at first, but after a software update, it lasts all day, and the phone's performance is outstanding.",
"I was skeptical about the LG air purifier because it seemed too small for my room, but it efficiently cleans the air and has significantly improved my allergies.",
"My initial experience with the LG vacuum cleaner was disappointing due to a lack of suction, but after cleaning the filters, it's now powerful and makes cleaning a breeze.",
"I wasn't impressed with the LG smartwatch at first because of limited app options, but regular updates have made it an essential gadget that I now rely on daily."
]
# 데이터프레임 생성
data = {'conversation': lg_reviews} # 값이 리스트인 딕셔너리 자료형
df = pd.DataFrame(data) # 판다스 데이터 프레임을 구성
# 감정분석 함수 생성
def analyze_sentiment(text):
blob = TextBlob(text) # TextBlob 객체를 생성
score = blob.sentiment.polarity # 감정 점수 계산
return score
# 감정 분석 점수 컬럼 추가
df['sentiment'] = df['conversation'].map(analyze_sentiment)
print( df )
문제2. 위에서 출력된 숫자 데이터를 이용해서 라인 그래프로 시각화를 하기위해 y축 데이터에 해당하는 감정점수를 추출하시오.
y_data =df['sentiment'].tolist() # df 데이터 프레임에 sentiment 컬럼의 값을 추출해서
y_data # 대괄호로 둘러싼 리스트 변수로 생성
문제3. y축 데이터에 대한 x축 데이터로 생성하시오.
x_data =df.index.tolist()
x_data
문제4. ploty 라인 그래프로 위의 결과를 시각화 하시오.
import plotly.express as px
fig = px.line(x=x_data, y=y_data)
fig.show()
문제 5. 엘사의 영화 시간 순서대로 저장한 엘사의 대사 30개를 가지고 데이터 프레임을 생성하는데 감정점수도 맨 끝에 추가해서 생성하시오.
import pandas as pd
from textblob import TextBlob
# 엘사의 임의 대사 30개 생성 (처음에 평온한 긍정, 중간에 부정, 마지막에 큰 폭으로 긍정)
elsa_lines = [
"Elsa: It's a beautiful morning in Arendelle.", # Calm positive
"Elsa: The day feels promising and peaceful.",
"Elsa: Everything is serene and tranquil.",
"Elsa: I feel content and relaxed today.",
"Elsa: The air is fresh and soothing.",
"Elsa: I enjoy the calm atmosphere.",
"Elsa: My heart is light and happy.",
"Elsa: It's nice to have a quiet moment.",
"Elsa: Life is good and simple right now.",
"Elsa: I'm grateful for this peaceful time.", # End of positive phase
"Elsa: I sense something unsettling in the air.", # Start of negative
"Elsa: There's a growing tension around me.",
"Elsa: I feel uncertain and uneasy.",
"Elsa: The situation is getting complicated.",
"Elsa: Problems seem to be arising everywhere.",
"Elsa: I feel overwhelmed and stressed.",
"Elsa: There is a storm brewing inside me.",
"Elsa: Everything is falling apart.",
"Elsa: I am lost and confused.",
"Elsa: This is a dark and challenging time.", # Negative peak
"Elsa: I must find a way through this.", # Start of recovery
"Elsa: I can see a light at the end of the tunnel.",
"Elsa: Solutions are beginning to appear.",
"Elsa: Hope is coming back into my life.",
"Elsa: I am regaining my strength and confidence.",
"Elsa: Things are turning around for the better.",
"Elsa: I am ready to face challenges head-on.",
"Elsa: The sun is shining brighter in my heart.",
"Elsa: I believe in a positive future.",
"Elsa: Everything is possible with love and courage!" # Strong positive ending
]
# 데이터프레임 생성
data = {'conversation': elsa_lines} # 값이 리스트인 딕셔너리 자료형
df = pd.DataFrame(data) # 판다스 데이터 프레임을 구성
# 감정분석 함수 생성
def analyze_sentiment(text):
blob = TextBlob(text) # TextBlob 객체를 생성
score = blob.sentiment.polarity # 감정 점수 계산
return score
# 감정 분석 점수 컬럼 추가 ( 엘사의 대사를 analyze_sentiment 에 입력해서 점수계산)
df['sentiment'] = df['conversation'].map(analyze_sentiment)
df
문제 6. 영화의 흐름에 따라 감정이 어떻게 변화는지 라인 그래프로 시각화 하시오.
import pandas as pd
from textblob import TextBlob
# 엘사의 임의 대사 30개 생성 (처음에 평온한 긍정, 중간에 부정, 마지막에 큰 폭으로 긍정)
elsa_lines = [
"Elsa: It's a beautiful morning in Arendelle.", # Calm positive
"Elsa: The day feels promising and peaceful.",
"Elsa: Everything is serene and tranquil.",
"Elsa: I feel content and relaxed today.",
"Elsa: The air is fresh and soothing.",
"Elsa: I enjoy the calm atmosphere.",
"Elsa: My heart is light and happy.",
"Elsa: It's nice to have a quiet moment.",
"Elsa: Life is good and simple right now.",
"Elsa: I'm grateful for this peaceful time.", # End of positive phase
"Elsa: I sense something unsettling in the air.", # Start of negative
"Elsa: There's a growing tension around me.",
"Elsa: I feel uncertain and uneasy.",
"Elsa: The situation is getting complicated.",
"Elsa: Problems seem to be arising everywhere.",
"Elsa: I feel overwhelmed and stressed.",
"Elsa: There is a storm brewing inside me.",
"Elsa: Everything is falling apart.",
"Elsa: I am lost and confused.",
"Elsa: This is a dark and challenging time.", # Negative peak
"Elsa: I must find a way through this.", # Start of recovery
"Elsa: I can see a light at the end of the tunnel.",
"Elsa: Solutions are beginning to appear.",
"Elsa: Hope is coming back into my life.",
"Elsa: I am regaining my strength and confidence.",
"Elsa: Things are turning around for the better.",
"Elsa: I am ready to face challenges head-on.",
"Elsa: The sun is shining brighter in my heart.",
"Elsa: I believe in a positive future.",
"Elsa: Everything is possible with love and courage!" # Strong positive ending
]
# 데이터프레임 생성
data = {'conversation': elsa_lines} # 값이 리스트인 딕셔너리 자료형
df = pd.DataFrame(data) # 판다스 데이터 프레임을 구성
# 감정분석 함수 생성
def analyze_sentiment(text):
blob = TextBlob(text) # TextBlob 객체를 생성
score = blob.sentiment.polarity # 감정 점수 계산
return score
# 감정 분석 점수 컬럼 추가 ( 엘사의 대사를 analyze_sentiment 에 입력해서 점수계산)
df['sentiment'] = df['conversation'].map(analyze_sentiment)
df
y_data =df['sentiment'].tolist() # df 데이터 프레임에 sentiment 컬럼의 값을 추출해서
y_data # 대괄호로 둘러싼 리스트 변수로 생성
x_data =df.index.tolist()
x_data
import plotly.express as px
fig = px.line(x=x_data, y=y_data)
fig.show()
오늘의 마지막 문제. 최근 티몬 사태에 대한 해외 감정 반응을 시각화 하시오!
최근 티몬(TMON, 티켓몬스터) 사태는 여러 문제로 인해 많은 관심을 받고 있습니다. 주로 재정적 어려움, 운영 문제, 경쟁 심화가 주요 이슈로 부각되고 있습니다. 아래는 티몬 사태에 대한 요약입니다. 1. 재정적 어려움누적 적자: 티몬은 지속적인 적자를 기록해왔습니다. 특히, 공격적인 할인 전략이 지속 가능하지 않다는 비판을 받으며, 이는 투자자들에게 우려를 안겼습니다 (Paris 2024 Olympics). 이러한 적자는 티몬의 장기적인 생존 가능성을 위협하고 있습니다.IPO 취소: 2022년에 티몬은 자금 조달과 재정 안정을 위해 기업 공개(IPO)를 계획했으나, 시장 상황과 내부 문제로 인해 상장이 연기되었습니다 (Paris 2024 Olympics) (뉴스1). 이로 인해 추가적인 자금 압박이 가중되었습니다.자금 조달 어려움: 티몬은 새로운 투자 유치에 어려움을 겪고 있습니다. 수익성에 대한 의구심과 경쟁력 약화로 인해 투자자들이 신중한 태도를 보이고 있으며, 이는 기술 투자 및 서비스 개선을 위한 재정적 여력을 제한하고 있습니다 (뉴스1).
import pandas as pd
from textblob import TextBlob
tmon_wemake_reviews = [
"I ordered a product from TMON, and it's been over a week with no delivery. Customer service is unresponsive and utterly useless.",
"Tried using a discount coupon on Wemakeprice, but it wouldn't apply. Felt like I was being scammed.",
"TMON's app keeps crashing, making it impossible to complete a purchase. I'm really disappointed.",
"Wemakeprice promised a 24-hour delivery, but my order hasn't even been shipped after three days.",
"I was excited about a sale on TMON, but the prices suddenly increased at checkout. This feels misleading.",
"Wemakeprice customer support keeps giving me the runaround about my refund. This is very frustrating.",
"TMON's inventory shows items in stock, but they cancel orders due to availability issues. It's unreliable.",
"I experienced several technical issues with Wemakeprice's website, making shopping a hassle.",
"TMON canceled my order without explanation. Now, I have to wait for a refund that’s taking forever.",
"Wemakeprice keeps advertising false promotions that don't apply when checking out. It's deceptive.",
"TMON's delivery service is the worst I've encountered. My package was lost, and they can't trace it.",
"Wemakeprice's return policy is unclear, and I am stuck with a faulty product. Very unsatisfied.",
"Customer service at TMON doesn't seem to care about customer satisfaction. They just ignore complaints.",
"I've been waiting for a refund from Wemakeprice for weeks, and nobody has been helpful. I'm losing patience.",
"TMON's payment process is broken. I had multiple failed transactions and no resolution in sight.",
"Wemakeprice seems to be falling apart. Orders are canceled, and the site barely works.",
"After repeated issues with TMON, I've decided to stop using their service. It's not worth the hassle.",
"Wemakeprice's promotions are just bait. They lure you in but never honor the discounts. Very disappointing.",
"I've given TMON multiple chances, but their service quality keeps declining. It's a disaster now.",
"Wemakeprice has become unreliable and frustrating to use. I'm looking for alternatives as they continue to fail."] # Strong positive ending
# 데이터프레임 생성
data = {'conversation': tmon_wemake_reviews} # 값이 리스트인 딕셔너리 자료형
df = pd.DataFrame(data) # 판다스 데이터 프레임을 구성
# 감정분석 함수 생성
def analyze_sentiment(text):
blob = TextBlob(text) # TextBlob 객체를 생성
score = blob.sentiment.polarity # 감정 점수 계산
return score
# 감정 분석 점수 컬럼 추가
df['sentiment'] = df['conversation'].map(analyze_sentiment)
df
y_data =df['sentiment'].tolist() # df 데이터 프레임에 sentiment 컬럼의 값을 추출해서
y_data # 대괄호로 둘러싼 리스트 변수로 생성
x_data =df.index.tolist()
x_data
import plotly.express as px
fig = px.line(x=x_data, y=y_data, labels={'x': 'REVIEWS', 'y': 'Sentiment Polarity'}, title="TMON_WEMAKE_REVIEWS")
fig.show()