2.Python List - salvarezmeneses/DataSciencePython GitHub Wiki
Listas
- Una lista es un tipo de dato contenedor (puede contener diferentes tipos de variables)
- Son creadas con: [ ]
- Las Listas pueden contener listas.
- Índice de base cero(inicia in 0)
- Los indices pueden empezar desde el final usando -
se requiere Almacenar la altura de todos los integrantes de la familia
Heigth = 1.73
Heigth = 1.68
Heigth = 1.71
Heigth = 1.89
Inconveniente = una variable no puede almacenar varios valores.
# Listas Válidas.
[1, 3, 4, 2] B. [1, 2, 3], [4, 5, 7](/salvarezmeneses/DataSciencePython/wiki/1,-2,-3],-[4,-5,-7) C. [1 + 2, "a" * 5, 3]
Sintaxis
- List[start:end] selects index from start until end-1 (end is not included)
- ex[:5] would select the first five elements
- ex[1:5] would select from the second to the fifth Element
- ex[-4:] would select the last four elements
- ex[-2:-1] would select the second last element
a = "is" b = "nice" my_list = ["my", "list", a, b]
-
To subset lists of lists: ex[list index][element index]
-
Adding new elements to list: ex+[new element]
-
Deleting from list: del(ex[element])
-
Copying list x
-
y=x only copies de reference that points to a list in memory, every change to y changes x too. (reference-based copy)
-
y=list(x) or y=x[:] points to a new list in memory. Changes in y does not change x (explicit copy)
-
In lists you can change, add and remove. Doing math Operations over the entire collection can be problematic
; is used to place commands on the same line
Functions
Pieces of reusable code that solve a particular task.
help(): returns information about a function, like arguments and what they return.
type(): returns the type of a variable
print(): displays the argument
max(): returns the maximum value of a group of numbers
round(a,b): rounds number a with a precision of b decimal places. If b is not specified, Python rounds the number to the closest integer.
str(), int(), bool(), float(), complex(,[]): converts to the type of variable specified
len(): returns the length of a list
sorted(iterable, key=None, reverse=false): returns a new list containing all items from the iterable in ascending order.
Methods Functions that belong to Python objects. Objects have methods associated depending on the type of the Object Careful: Some methods change the object they are called on. Object Method name Method Output List list.index(element) Returns the index of the element String string.capitalize() Capitalized the first letter of string String string.replace(characters to be replaced, characters to replace with) Replaces the indicated characters of a string with the indicated characters String string.index(letter) Returns the index of the letter in the string List list.append(element) Adds the element to eh end of the list String string.upper() Capitalize every letter String string.lower()
String
string.count(character)
Counts how many times a character is on the string. Careful, it is case sensitive
List
list.count(element)
Counts how many times an element is on the list. Careful, it is case sensitive
List
list.remove(element)
Removes from the list the first time the element appears
List
list.reverse()
Reverses the list
Packages:
Directory of Python scripts
Each script = module. Specific functions, methods, types
Not all packages are available in Python by default: they have to be installed
pip: package maintenance system for Python
pip.readthedocs.org/en/stable/installing/
Download get-pip.py
Terminal execute: python3 get-pip.py
Now use pip to install Python packages
Ex Terminal: pip3 install numpy
Package installed
After the package is installed, it needs to be imported
Script: import package as nickname
Ex: import numpy as np
Using a nickname is useful because everytime you want to use something from the package you need to call it
Ex: numpy.array() would be better to write np.array()
You can also import only an specific part of a package
from package import function
Ex: from numpy import array
There would be no need to use no.array any more, only array would be enough
Package
Use
Numpy
Efficiently work with arrays
Matplotlib
Data visualization
Scikit-learn
Machine learning
Math
Math. Has constants like math.pi or functions like math.radians(angle °)
Scipy
Science
Scipy.linalg
Linear algebra
Numpy
pip3 install numpy Import numpy as np
NumPyArray: numpy.array() Similar to lists but math Operations can be made over the entire array Easy and fast Can only contain values of a single type: either int, float, double, booleans, string Applies type coercion: if you try to build an array with different types of elements, some elements' types are changed to end up with a homogeneous list Has its own methods nparray.shape Attribute size of the array: rows,columns To select a specific element of a matrix with 2 or more dimensions: nparray[row][column] or nparray[row,column] or nparray[restart:rowend+1, columstart:columend+1]
Functions NumPy has some functions similar to regular functions, but NumPy functions are faster because they force the same type of data
numpy.mean(array): numpy.median(array): np.std(array): np.corrcoef(array): np.sum(): np.sort(): np.append(arrays): np.round(): np.random.normal(mean, std,# samples): np.column_stack(): pastes columns together np.transpose()
Statistics:
When max or min numbers seem to be outliers-> calculate mean and median, this lets us analyze if indeed the min or max number is an outlier