DEV Community

Palak Hirave
Palak Hirave

Posted on

Day 25 of 100

Whilst I had heard about the Pandas library, today I learnt how to use it. I also took some time later to just go though the 'getting started' part of the documentation(which can be found here). I took some notes and then did a project in which you have to guess all 50 of the United States. This list of various bits of code is ordered from what I did first and my final project at the bottom.

notes.py

print("------------------------------------------------------")

import csv
# Reading a file and collecting data from one of its
#   columns and converting it to an integer
with open("weather_data.csv") as data_file:
    data = csv.reader(data_file)
    temp = []
    for row in data:
        if row == ['day', 'temp', 'condition']:
            pass
        else:
            degree = int(row[1])
            temp.append(degree)
    print(temp)

print("------------------------------------------------------")

import pandas as pd
# With Pandas
data = pd.read_csv('weather_data.csv')
print(data["temp"])

print("------------------------------------------------------")

# Turns DataFrame to dictionary
data_dict = data.to_dict()
print(data_dict)

# Turns Series to list
temp_list = data["temp"].to_list()
print(temp_list)

print("------------------------------------------------------")

average = sum(temp_list) / len(temp_list)
# OR
average = data["temp"].mean()

print(data["temp"].max())

print("------------------------------------------------------")

# Get data in columns
print(data["condition"])
print(data.condition) #Behind the scenes, pandas
                    # converts each of the columns into attributes
# Get data in rows
print(data[data.day == "Monday"])
print(data[data.temp == data.temp.max()])

monday = data[data.day == "Monday"]
fahrenheit = monday["temp"] * 1.8 + 32
print(fahrenheit)

print("------------------------------------------------------")

# Create DataFrame from scratch
newdata_dict = {"names" : ["John", "Rebecca", "Myles", "Styles", "Anthony"],
                "test scores" : [24, 99, 57, 78, 80]}

data = pd.DataFrame(newdata_dict)
data.to_csv("new_data.csv", index=False)

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

new_data.csv (created once notes.py runs)

names,test scores
John,24
Rebecca,99
Myles,57
Styles,78
Anthony,80
Enter fullscreen mode Exit fullscreen mode

Squirrels!

The squirrel data for this project can be found here.

import pandas as pd
# TODO : take the Primary Fur Color column and make a
#  new .csv file that contains the three colours and
#  how many squirrels are in each one

black = 0
gray = 0
cinnamon = 0

data = pd.read_csv("squirrel_data.csv")
for color in data["Primary Fur Color"] :
    if color == "Black" :
        black += 1
    elif color == "Gray" :
        gray += 1
    else:
        cinnamon += 1

small_squirrel_data = {"Colour" : ["Black", "Gray", "Cinnamon"],
                       "Count" : [black, gray, cinnamon],}
data = pd.DataFrame(small_squirrel_data)
data.to_csv("small_squirrel_data.csv", index=False)

Enter fullscreen mode Exit fullscreen mode

Output CSV file (small_squirrel_data.csv)

Colour,Count
Black,103
Gray,2473
Cinnamon,447
Enter fullscreen mode Exit fullscreen mode

Main Project - Guess the USA's States

main.py

import pandas as pd
import turtle
import time

screen = turtle.Screen()
screen.title("U.S.A State Game")
image = "blank_states_img.gif"
screen.addshape(image)
screen.setup(height=500,width=730)
screen.bgpic("blank_states_img.gif")
turtle.shape(image)

# TODO : Get x and y values for all states on the image
# def mouse_click_coord(x,y):
#     print(x,y)
#
# turtle.onscreenclick(mouse_click_coord)
# turtle.mainloop()

game_on = True
states_guessed = 0
correct_guess = ""
guessed_states = []
pen = turtle.Turtle()
pen.penup()
pen.hideturtle()
pen.speed(0)

while game_on:
    answer_state = screen.textinput(title="Guess a state",
                                    prompt=f"{states_guessed}/50 states guessed", )

    states_list = pd.read_csv("50_states.csv")

    for states in states_list.state:
        if states == answer_state.title():
            correct_guess = answer_state.title()

            if correct_guess not in guessed_states:
                states_guessed += 1
                guessed_states.append(correct_guess)
                row_list = states_list[states_list.state == correct_guess]
                row_list = row_list.to_dict()
                xcor = list(row_list['x'].values())[0]
                ycor = list(row_list['y'].values())[0]
                pen.goto(x = xcor, y = ycor)
                pen.write(correct_guess, align="right", font=("Courier", 7, "bold"))

    if states_guessed == 50:
        screen.textinput("Finished", "You have guessed all the states!")
        time.sleep(1)
        game_on = False

screen.exitonclick()
Enter fullscreen mode Exit fullscreen mode

50_states.csv
Note - the coordinates may not be exact for everyone, their a bit off for me as well but I can't be asked to individually change them all.

state,x,y
Alabama,139,-77
Alaska,-204,-170
Arizona,-203,-40
Arkansas,57,-53
California,-297,13
Colorado,-112,20
Connecticut,297,96
Delaware,275,42
Florida,220,-145
Georgia,182,-75
Hawaii,-317,-143
Idaho,-216,122
Illinois,95,37
Indiana,133,39
Iowa,38,65
Kansas,-17,5
Kentucky,149,1
Louisiana,59,-114
Maine,319,164
Maryland,288,27
Massachusetts,312,112
Michigan,148,101
Minnesota,23,135
Mississippi,94,-78
Missouri,49,6
Montana,-141,150
Nebraska,-61,66
Nevada,-257,56
New Hampshire,302,127
New Jersey,282,65
New Mexico,-128,-43
New York,236,104
North Carolina,239,-22
North Dakota,-44,158
Ohio,176,52
Oklahoma,-8,-41
Oregon,-278,138
Pennsylvania,238,72
Rhode Island,318,94
South Carolina,218,-51
South Dakota,-44,109
Tennessee,131,-34
Texas,-38,-106
Utah,-189,34
Vermont,282,154
Virginia,234,12
Washington,-257,193
West Virginia,200,20
Wisconsin,83,113
Wyoming,-134,90
Enter fullscreen mode Exit fullscreen mode

Top comments (0)