-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal3.csv
More file actions
We can make this file beautiful and searchable if this error is corrected: Illegal quoting in line 4.
247 lines (187 loc) · 9.31 KB
/
final3.csv
File metadata and controls
247 lines (187 loc) · 9.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
APIs
import json # a library for handling an extremely commmon cross-platform file format
import requests # a library of functions that enable use of APIs
response = requests.get("http://api.open-notify.org/iss-now.json")
# Website where api is hosted
print(response.text) (Gets us the responses of the API)
data = json.loads(response.text) # This loads a dictionary
type(data)
float(data['iss_position']['latitude'])
#For a tuple, you just
((float(data['iss_position']['latitude']), float(data['iss_position']['longitude'])
---
response = requests.get('https://api.g7vrd.co.uk/v1/satellite-passes/%s/%s/%s.json?minelevation=%s&hours=%s'
%('25544', '41.8781', '-87.6298','50','24' ))
print(response.text)
data = json.loads(response.text)
data['passes']
Notice the use of %s and %( ). This is a standard part of python called string formatting. It's really handy. Rather than %s (meaning it needs a string) you can also do %f for floats, %d for integers, etc. To learn more, look at this resource.
---------------------
import requests
def get_astronauts_in_ISS():
# The API endpoint for getting the current number of people in space
api_url = "http://api.open-notify.org/astros.json"
# Make a GET request to the API
response = requests.get(api_url)
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON response
data = response.json()
num_astronauts = data['number']
astronauts = data['people']
# Print the number of astronauts
print(f"Number of astronauts in the ISS: {num_astronauts}")
print("Astronauts in the ISS:")
for astronaut in astronauts:
print(f"- {astronaut['name']}, Craft: {astronaut['craft']}")
else:
print("Failed to retrieve data from the API.")
get_astronauts_in_ISS()
---------
import requests
def get_weather_data(api_key, city):
"""Fetches real-time weather data for a specified city using the OpenWeatherMap API."""
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
weather_data = response.json()
if weather_data["cod"] != "404":
weather = weather_data["main"]
current_temperature = weather["temp"]
current_pressure = weather["pressure"]
current_humidity = weather["humidity"]
weather_description = weather_data["weather"][0]["description"]
return (current_temperature, current_pressure, current_humidity, weather_description)
else:
return None
# Example usage
api_key = "YOUR_API_KEY"
city_name = "New York"
weather_info = get_weather_data(api_key, city_name)
if weather_info:
print(f"Weather in {city_name}:")
print(f"Temperature: {weather_info[0]}")
print(f"Pressure: {weather_info[1]}")
print(f"Humidity: {weather_info[2]}")
print(f"Description: {weather_info[3]}")
else:
print("City not found.")
----------------
Methods from the requests package return Response objects. One of the most important properties of the response is its status code, which is printed by default but which we can also get explicitly.
Here are some of the most common status codes you might encounter:
200, OK. Standard response for successful HTTP requests. The actual response will depend on the request method used.
301, Moved Permanently. The server is redirecting you to a different endpoint. This and all future requests should be directed to the given URL. This can happen when a company switches domain names, or an endpoint name is changed.
303, See Other. The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE), the client should presume that the server has received the data and should issue a redirect with a separate GET message. Your web browser automatically fetches the new URL but web crawlers do not usually do this unless you specify it.
400, Bad Request. The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
401, Unauthorized. Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
403, Forbidden. The request was a valid request, but the server is refusing to respond to it. 403 error semantically means "unauthorized", i.e. the user does not have the necessary permissions for the resource.
404, Not Found. The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
500, Internal Server Error. A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
503, Service Unavailable. The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.
504, Gateway Timeout. The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.[
-----------
Plotting
from IPython.core.display import HTML
from IPython.lib.display import YouTubeVideo
def css_styling():
styles = open("custom.css", "r").read()
return HTML(styles)
css_styling()
from IPython.display import Image
Image(filename='visualization_raw_chart.png')
Image(filename='visualization_heatmap.png')
----------
Why did the O-rings crack?
There were rumblings at NASA prior to the Challenger launch that defects in the O-rings occurred at cold temperatures. This data was looked at by a large number of people, but this is how it was presented to senior management (the people actually tasked with making the decision of whether it was safe or not to launch the rocket).
Image(filename='challenger_original.png')
Image(filename='challenger_remade.png')
Image(filename='fox_news.png')
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 2, 3, 4])
(regular plot)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
fig = plt.figure(figsize = (10, 7))
ax = fig.add_subplot(3, 1, 1)
ax.plot([1, 2, 3, 4], [1, 2, 3, 4], color = 'steelblue', marker = 'o')
ax.plot([7, 8 , 9], [7, 8 , 9], color= 'orange', marker='^')
ax = fig.add_subplot(3, 1, 2)
ax.plot([7, 8 , 9], [7, 8 , 9], color= 'orange', marker='^')
ax = fig.add_subplot(3, 1, 3)
ax.plot([11, 12, 13], [11, 12, 13], color ='red')
------------
import sys
import numpy as np
import random as rand
import matplotlib as mpl
import matplotlib.cm as cm
# Change the baseline font
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = ['DejaVu Sans']
#Create the figure
fig = plt.figure( figsize = (6, 4) )
ax = fig.add_subplot(1,1,1)
# We should add a label to our dataset that will go into a legend
ax.plot(x, y, label = "Quadratic", color = 'steelblue', linewidth = 3, marker = 'o', markersize = 10)
# Now we can label the axes. Always label your axes! Who knows what is in the graph otherwise
font_size = 15
ax.set_xlabel("$x$", fontsize = 2*font_size)
ax.set_ylabel("$f(x)$", fontsize = 1.6*font_size)
# Display legend
ax.legend(loc='best', frameon=False, fontsize = font_size, markerscale = 1.2)
#Adding a label
ax.text(90, 15, "(A)", fontsize = 1.2 * font_size)
#Turn off the spines
for axis in ['bottom','left']:
ax.spines[axis].set_linewidth(2)
ax.spines[axis].set_position(("axes", -0.02))
for axis in ['top','right']:
ax.spines[axis].set_visible(False)
#We'll also need to turn off the ticks on the axes that we turned off
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
#Change the y-scale to log
ax.set_yscale('log')
#Save the figure
plt.savefig('quadratic_logscale_half_frame.png')
----------
good looking graph
with plt.style.context('ggplot'):
fig = plt.figure( figsize = (6, 4) )
ax = fig.add_subplot(1,1,1)
# We should add a label to our dataset that will go into a legend
ax.plot(x, y, label = "Quadratic")
# Now we can label the axes. Always label your axes! Who knows what is in the graph otherwise
ax.set_xlabel("$x$", fontsize = 1.6*font_size)
ax.set_ylabel("$f(x)$", fontsize = 1.6*font_size)
# Display legend
ax.legend(loc='best', frameon=False)
--------
(bar graphs)
def read_gpa_data(filepath):
'''
Reads in the gpa data file of undergraduate students
input:
filepath - str, filename
output:
gpas - list, float gpas
'''
data = [l.strip().split(',') for l in open(filepath).readlines()]
gpas = []
for gpa_line in data:
try:
fgpa = float(gpa_line[0])
if fgpa < 4.0:
gpas.append(fgpa)
except:
pass
return gpas
gpas = read_gpa_data('gpa_data.csv')
gpas[:10]
(The bins = 20 part is important)
fig = plt.figure( figsize = (6, 4.5))
ax = fig.add_subplot(1, 1, 1)
ax.hist(gpas, bins = 20, color = 'steelblue')
ax.set_xlabel('GPA', fontsize = 1.6 * font_size)
ax.set_ylabel('Count', fontsize = 1.6 * font_size)