Python

Intermediate Importing Data in Python

1. Importing flat files from the web: your turn! # Import package from urllib.request import urlretrieve # Import pandas import pandas as pd # Assign url of file: url url = 'https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv' # Save file locally urlretrieve(url, 'winequality-red.csv') # Read file into a DataFrame and print its head ## ('winequality-red.csv', <http.client.HTTPMessage object at 0x000000001FBF52C8>) df = pd.read_csv('winequality-red.csv', sep=';') print(df.head()) ## fixed acidity volatile acidity citric acid ... sulphates alcohol quality ## 0 7.

Continue reading

Introduction to Importing Data in Python

1. Importing entire text files # Open a file: file file = open('c:/blogdown/moby_dick.txt', mode='r') # Print it print(file.read()) # Check whether file is closed ## CHAPTER 1. Loomings. ## ## Call me Ishmael. Some years ago--never mind how long precisely--having ## little or no money in my purse, and nothing particular to interest me on ## shore, I thought I would sail about a little and see the watery part of ## the world.

Continue reading

Supervised Learning with Scikit-Learn

1. The Iris dataset in scikit-learn from sklearn import datasets import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') iris = datasets.load_iris() type(iris) ## <class 'sklearn.utils.Bunch'> print(iris.keys()) ## dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename']) print(iris.DESCR) ## .. _iris_dataset: ## ## Iris plants dataset ## -------------------- ## ## **Data Set Characteristics:** ## ## :Number of Instances: 150 (50 in each of three classes) ## :Number of Attributes: 4 numeric, predictive attributes and the class ## :Attribute Information: ## - sepal length in cm ## - sepal width in cm ## - petal length in cm ## - petal width in cm ## - class: ## - Iris-Setosa ## - Iris-Versicolour ## - Iris-Virginica ## ## :Summary Statistics: ## ## ============== ==== ==== ======= ===== ==================== ## Min Max Mean SD Class Correlation ## ============== ==== ==== ======= ===== ==================== ## sepal length: 4.

Continue reading

Python Data Science - part 1

1. Single Parameter Function # Define shout with the parameter, word def shout(word): """Print a string with three exclamation marks""" # Concatenate the strings: shout_word shout_word = word + '!!!' # Print shout_word print(shout_word) # Call shout with the string 'congratulations' shout("Congratulations") ## Congratulations!!! 2. Functions that return single values # Define shout with the parameter, word def shout(word): """Return a string with three exclamation marks""" # Concatenate the strings: shout_word shout_word = word + "!

Continue reading

Linear Models - Scikit Learn

1. Linear Models The target value is expected to be a linear combination of the features. 1.1. Ordinary Least Squares (OLS) The OLS is a optimization math technique that aim to find the better adjustment for a set data and try to minimize the residual sum of squares between the observed targets in the dataset and the targets predicted by the linear approximation. from sklearn import linear_model reg = linear_model.

Continue reading

TensorFlow 2 - Quickstart for Beginners

from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10) ]) predictions = model(x_train[:1]).numpy() ## WARNING:tensorflow:Layer flatten is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because it's dtype defaults to floatx.

Continue reading

Iterables versus Iterators

1. Defining a list flash1 = ['jay garrick', 'barry allen', 'wally west', 'bart allen'] a = 1

Continue reading

A Game of Chance

"""Simulating the dice game Craps""" ## 'Simulating the dice game Craps' import random def roll_dice(): """Roll two dice and return their face values as a tuple.""" die1 = random.randrange(1,7) die2 = random.randrange(1,7) return (die1, die2) def display_dice(dice): """Display one roll of the two dice.""" die1, die2 = dice print(f'Player rolled {die1} + {die2} = {sum(dice)}') die_values = roll_dice() #first roll display_dice(die_values) # determine game status and point, based on first roll.

Continue reading

Functions

1. Defining functions def square(number): print("The square of", number, "is", number ** 2) square(7) ## The square of 7 is 49 2. Functions with multiple parameters def maximum(value1, value2, value3): max_value = value1 if value2 > max_value: max_value = value2 if value3 > max_value: max_value = value3 return max_value maximum(12, 27, 36) ## 36 maximum('yellow', 'red', 'orange') ## 'yellow' 3. Random-Number Generation import random random.seed(10) for roll in range(10): print(random.

Continue reading

Binary Search Algorithm

def binary_search(lista, item): low = 0 # low and high are part of the list thar you are searching for high = len(lista) - 1 while low <= high: #while you are not achieving one unique element middle = (low + high) // 2 # checking the central element guess = lista[middle] if guess == item: return middle if guess > item: # the guess are too high high = middle - 1 else: # the guess are too low low = middle + 1 return None my_list = [1, 3, 5, 7, 9] print(binary_search(my_list, 3)) ## 1 print(binary_search(my_list, -1)) ## None

Continue reading