Days25. csv 데이터, pandas 라이브러리
*weather_data.csv (데이터파일)
day,temp,condition
Monday,12,Sunny
Tuesday,14,Rain
Wednesday,15,Rain
Thursday,14,Cloudy
Friday,21,Sunny
Saturday,22,Sunny
Sunday,24,Sunny
*csv파일을 열고 각 라인을 읽어서 공백/특수기호 제거하고 data 리스트에 넣기
data = []
with open("./weather_data.csv") as csv_data:
contents = csv_data.readlines()
for line in contents:
data.append(line.strip())
print(data)
['day,temp,condition', 'Monday,12,Sunny', 'Tuesday,14,Rain', 'Wednesday,15,Rain', 'Thursday,14,Cloudy', 'Friday,21,Sunny', 'Saturday,22,Sunny', 'Sunday,24,Sunny']
>>> 넣긴 했으나, 각각의 데이터를 활용하기엔 또 콤마 단위로 분류를 해야하는 등 effort가 많이 소모됨
* 내장 라이브러리 사용
import csv
with open("./weather_data.csv") as csv_data:
contents = csv.reader(csv_data)
for row in contents:
print(row)
['day', 'temp', 'condition']
['Monday', '12', 'Sunny']
['Tuesday', '14', 'Rain']
['Wednesday', '15', 'Rain']
['Thursday', '14', 'Cloudy']
['Friday', '21', 'Sunny']
['Saturday', '22', 'Sunny']
['Sunday', '24', 'Sunny']
>>> 파이썬이 데이터 분석에 csv를 많이 사용되므로 csv 라이브러리가 내장되어 있음
>>> csv의 reader 메소드를 이용하면 좀 더 편하게 분류 가능함
* 온도 데이터만을 추출
import csv
with open("./weather_data.csv") as csv_data:
contents = csv.reader(csv_data)
temperatures = []
for row in contents:
if row[1] != 'temp':
temperatures.append(int(row[1]))
print(temperatures)
[12, 14, 15, 14, 21, 22, 24]
---------------------------------------------------------------------------------
* pandas 라이브러리 사용
>>> 파이썬 데이터 분석 라이브러리로 외부 라이브러리임. (설치 필요)
>>> https://pandas.pydata.org/
import pandas
data = pandas.read_csv("./weather_data.csv")
print(data)
day temp condition
0 Monday 12 Sunny
1 Tuesday 14 Rain
2 Wednesday 15 Rain
3 Thursday 14 Cloudy
4 Friday 21 Sunny
5 Saturday 22 Sunny
6 Sunday 24 Sunny
print(data["temp"]) # or print(data.temp)
0 12
1 14
2 15
3 14
4 21
5 22
6 24
*pandas를 통해 오픈한 csv의 데이터타입 : DataFrame
import pandas
data = pandas.read_csv("./weather_data.csv")
print(data)
print(type(data))
day temp condition
0 Monday 12 Sunny
1 Tuesday 14 Rain
2 Wednesday 15 Rain
3 Thursday 14 Cloudy
4 Friday 21 Sunny
5 Saturday 22 Sunny
6 Sunday 24 Sunny
<class 'pandas.core.frame.DataFrame'>
* 2 type of pandas data structure : Series, DataFrame
- series : 각각의 컬럼 개념
- DataFrame : 하나의 sheet 개념
*series의 메소드들
to_list() : 리스트화
to_dict() : 딕셔너리화
mean() : 평균
max() : 최대
min() : 최소
data_dict = data.to_dict()
print(data_dict)
temp_list = data["temp"].to_list()
print(temp_list)
print(sum(temp_list)/len(temp_list))
print(f"average temperature : {data['temp'].mean()}")
print(f"max temperature : {data['temp'].max()}")
print(f"min temperature : {data['temp'].min()}")
# data.to_dict()
{'day': {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}, 'temp': {0: 12, 1: 14, 2: 15, 3: 14, 4: 21, 5: 22, 6: 24}, 'condition': {0: 'Sunny', 1: 'Rain', 2: 'Rain', 3: 'Cloudy', 4: 'Sunny', 5: 'Sunny', 6: 'Sunny'}}
# data["temp"].to_list() or data.temp.to_list()
[12, 14, 15, 14, 21, 22, 24]
# print(sum(temp_list)/len(temp_list))
17.428571428571427
# data['temp'].mean() or data.temp.mean()
average temperature : 17.428571428571427
# data['temp'].max() or data.temp.max()
max temperature : 24
# data['temp'].min() or data.temp.min()
min temperature : 12
* 같은 조회결과
print(data["condition"])
print(data.condition)
0 Sunny
1 Rain
2 Rain
3 Cloudy
4 Sunny
5 Sunny
6 Sunny
Name: condition, dtype: object
0 Sunny
1 Rain
2 Rain
3 Cloudy
4 Sunny
5 Sunny
6 Sunny
Name: condition, dtype: object
* 행(row)에서 데이터 찾기
print(data[data.day == "Monday"]) # data에서 day가 Monday인 series 출력
print(data[data.temp == data.temp.max()]) # data에서 temp가 최대인 series 출력
print(data[data.temp == data.temp.min()]) # data에서 temp가 최소인 series 출력
print(data[data.temp >= data.temp.mean()]) # data에서 temp가 평균보다 큰 series 출력
day temp condition
0 Monday 12 Sunny
day temp condition
6 Sunday 24 Sunny
day temp condition
0 Monday 12 Sunny
day temp condition
4 Friday 21 Sunny
5 Saturday 22 Sunny
6 Sunday 24 Sunny
*특정 row의 특정 데이터만 추출
monday = data[data.day == "Monday"]
print(monday.condition)
print(monday.temp)
print(((monday.temp)*9/5)+32)
0 Sunny
Name: condition, dtype: object
0 12
Name: temp, dtype: int64
0 53.6
Name: temp, dtype: float64
* DataFrame 생성
# Create a dataframe from scratch
data_dict = {
"students": ["Amy", "James", "Angela"],
"scores": [76, 56, 65]
}
data = pandas.DataFrame(data_dict)
print(data)
data.to_csv("./new_data.csv")
students scores
0 Amy 76
1 James 56
2 Angela 65
그리고 해당경로에 new_data.csv 생성됨
--------------------------------------------------------------------------------------------------
* csv 데이터에서 원하는 컬럼을 기준으로 데이터별 카운트하여 별도의 csv로 생성해보기
import pandas
#https://data.cityofnewyork.us/Environment/2018-Central-Park-Squirrel-Census-Squirrel-Data/vfnx-vebw
squirrel_data = pandas.read_csv("./2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv")
grey = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Gray"])
red = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Cinnamon"])
black = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Black"])
data_dict = {
"Fur Color": ["Geay", "Cinnamon", "Black"],
"Count": [grey, red, black]
}
new_squirrel_data = pandas.DataFrame(data_dict)
print(new_squirrel_data)
new_squirrel_data.to_csv("./squirrel_count.csv")
>> 뉴욕 센트럴 파크에 사는 다람쥐 데이터에서 색깔별 카운팅하여 별도의 CSV파일을 생성함
Fur Color Count
0 Geay 2473
1 Cinnamon 392
2 Black 103
------------------------------------------------------------------------------------------------------
* 미국 주 알아맞히기 게임https://www.sporcle.com/ > us states 검색
Sporcle – World’s Largest Trivia Quiz Website
Play thousands of free online trivia quiz games. There is a fun quiz about virtually every topic imaginable: Geography, History, Sports, Music, TV and more!
www.sporcle.com
* main.py
import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S.A. states game")
# ----------------------------------------
screen.bgpic("./blank_states_img.gif") # 1
# ---------------------------------------- 1과 2의 차이는 뭘까?
# bgpic = "./blank_states_img.gif"
# screen.addshape(bgpic)
# turtle.shape(bgpic) # 세 라인 2
# print(state_input)
states_data = pandas.read_csv("./50_states.csv")
states_only_lists = states_data["state"].to_list()
# print(states_only_lists)
guessed_state = []
while len(guessed_state) < 50:
state_input = screen.textinput(
title=f"{len(guessed_state)}/50 States Correct",
prompt="What's another state's name?").title() #states_data["state"].lower()는 에러나는데 title()은 되는구나
if state_input in states_only_lists:
t = turtle.Turtle()
t.hideturtle()
t.pu()
guessed_state.append(state_input)
matched_data = states_data[states_data["state"] == state_input]
t.goto(int(matched_data.x), int(matched_data.y))
# t.write(matched_data.state)
t.write(state_input)
# t.write(matched_data.state.item())
screen.exitonclick() # exit the window if click
** exit을 입력하면 맞추지 못한 주를 csv파일로 남기고 종료하도록 기능 추가한 최종버전
import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S.A. states game")
# ----------------------------------------
screen.bgpic("./blank_states_img.gif") # 1
# ---------------------------------------- 1과 2의 차이는 뭘까?
# bgpic = "./blank_states_img.gif"
# screen.addshape(bgpic)
# turtle.shape(bgpic) # 세 라인 2
# print(state_input)
states_data = pandas.read_csv("./50_states.csv")
states_only_lists = states_data["state"].to_list()
# print(states_only_lists)
guessed_state = []
while len(guessed_state) < 50:
state_input = screen.textinput(
title=f"{len(guessed_state)}/50 States Correct",
prompt="What's another state's name?").title() #lower()는 에러나는데 title()은 되는구나
#----------------exit을 입력하면 끝내고 맞춘 주를 csv파일에보관하고싶다.
if state_input == "Exit":
missed_states = []
for state in states_only_lists:
if state not in guessed_state:
missed_states.append(state)
missed_states_file = pandas.DataFrame(missed_states)
missed_states_file.to_csv("./missed_states_file.csv")
break
#-----------------------------------------------------------------
if state_input in states_only_lists:
t = turtle.Turtle()
t.hideturtle()
t.pu()
guessed_state.append(state_input)
matched_data = states_data[states_data["state"] == state_input]
t.goto(int(matched_data.x), int(matched_data.y))
# t.write(matched_data.state)
t.write(state_input)
# t.write(matched_data.state.item())