Está en la página 1de 6

RECURSOS PARA PROGRAMACIÓN

COSAS VARIAS

## Básico
help(math.cos) # Saber qué hace una función
lista.index(2) # El índice de un valor en especifico
type(a) # Tipo de variable

Abs (-2)
isinstance(a,str) #comprobar si (a) es str
max(1,2,3)
min(1,2,3)
a = 1,2,3,4 ó (1,2,3,4) #tupla
len(lista) # Longitud de un archivo
range(1,6,2) # 1, 3, 5

## Indice de una lista


una_lista[0]) # Primer elemento, 1
una_tupla[1]) # Segundo elemento, 2
una_lista[0:2]) # Desde el primero hasta el tercero, excluyendo este: 1, 2
una_tupla[:3]) # Desde el primero hasta el cuarto, excluyendo este: 1, 2, 3.0
una_lista[-1]) # El último: 4 + 0j
una_tupla[:]) # Desde el primero hasta el último
una_lista[::2]) # Desde el primero hasta el último, saltando 2: 1, 3.0
una_lista.append(1) # Añadir un valor

## Abrir y leer archivo


open(file, mode) # mode: ‘r’ read , ’a’ append , ‘w’ write , ‘x’ create

## Condicionales
if a (==, !=, <, >, <=, >=) b (and, and not, or) c :
elif <condition>:
<algo>
else:
<algo>

## Booleanos
True and False -> False
not False -> True
False + False -> 0

## Ciclos
while i < 4:
I += 1 # Sumar 1 en cada ciclo
Break # Romper el ciclo

For i in [1,3,4]:

## with
with open('file_path', 'w') as file: # Otra forma de escribir
file.write('hello world !')
## Funciones
def funcion1(a,b):
c=a*b
return c

## Ejecutar un archivo desde cmd


>python archivo.py

## Jupyter
%%timeit # Tiempo de ejecución de una celda
%matplotlib inline # Imprimir en el notebook

LIBRERIAS IMPORTANTES

## import math

math.cos()
math.sqrt()

## import numpy as np

np.__version__ #ver versión


np.array() #crear array
a.dtype #compobar el tipo de datos de (a)
a.astype(‘float’) #cambiar de tipo de varible
np.sum()
np.max()
np.sin()
np.pi
np.e
np.concatenate(array,np.array([1,2]) #añadir valores a un array

np.loadtxt("arc.csv",
skiprows=1, # Saltamos una línea,
usecols=(1, 2, 3), # Solo columnas 2, 3 y 4
delimiter=',') # Separados por comas

np.genfromtxt('arc.csv',
skip_header=3, #omitir las 3 primeras columnas
skip_footer= 10, #omitir las 10 últimas datos
delimiter=';',
usecols=(2,3,4),
dtype=str)

np.zeros(100) ó np.zeros([10,10]) #Array de 100 ceros


np.empty(100) #Array valores al azar
np.ones(100) #Array de 1’s
np.identity(4) #Matriz identidad 4x4
np.arange(0,2,0.5) # [0. 0.5 1. 1.5]
M = np.arange(36, dtype=float).reshape(4, 9) # Ejemplo combinado
np.linspace(0,2,5) # [0. , 0.5, 1. , 1.5, 2. ]
np.reshape(a, [3, 4]) # Si (a) tiene 12 elementos, lo pone en una matriz 3*4
a.append(1) # Agregarle un calor a un array (funciona igual para lista)
a[:5].copy # Crear una copia de (a)
np.mean(data1, axis=0) # Media de los datos
np.size(data) # Mirar el número total de datos
Data.shape # saber la forma en que están distribuidos los datos

np.linalg # Alberga funciones de algebra lineal (norm,inv,solve,det etc…)


np.dot () # Producto escalar
np.allclose() # Comprueba si dos arreglos son iguales en una tolerancia
np.isclose() # Comprueba si dos arreglos son iguales

## import matplotlib
## import matplotlib.pyplot as plt

(MIRAR TODOS LOS EJEMPLOS: http://matplotlib.org/gallery.html#pylab_examples)

fig = plt.figure() # Crear objeto


plt.figure(figsize=(8,8)) # Tamaño de la figura
fig.add_sbbubplot(111) # Anadir subplot
plt.scatter(x, y) # Scatter
plt.show() # Mostrar figura

f, ax = plt.subplots() # Otra forma de crear figuras y subplots


ax.plot(x, y)
ax.set_xlim(0, 40)
ax.fill_between(x, y1, y2, facecolor='#4f88b1', edgecolor='none')
ax.set_xlabel(‘x’, fontsize=12)
ax.set_ylabel(‘y’)
plt.yticks(fontsize=12) # Tamaño de los valores
ax.set_title('Simple plot')
fig.savefig('yourfilename.png') # Guardar figura

“plt.subplots() es una función que devuelve una tupla que contiene una figura y objeto (s) de ejes. Por lo
tanto, al usar fig, ax = plt.subplots(), desempaquetar esta tupla en las variables fig y ax. Tener fig es útil si
desea cambiar los atributos de nivel de figura o guardar la figura como un archivo de imagen más adelante
(por ejemplo, con fig.savefig('yourfilename.png')”

plt.axhline(valor) # Crear línea horizontal


plt.axvline(valor) # Crear línea vertical
np.percentile(datos, range(101)) # Hallar los percentiles del conjunto de datos
Hist, bins = np.histogram(datos, 25) # Construir histogramas con numpy

plt.matshow(tablero,cmap=plt.cm.Blues_r) # Tablero de ajedrez (tablero: matriz 0,1)

## import scpy.stats as scp

scp.skew(datos) #Coeficiente de simetría

## from datetime import datetime


https://www.programiz.com/python-programming/datetime/strptime
a=datetime.strptime(data,’%Y%j) # Convertir los datos de fecha a formato de años julianos
a[213].year -> ejm 2006
a[213].month -> 08 (agosto)
a.[213].day -> 1

## from plotnine import *

https://monashdatafluency.github.io/python-workshop-base/modules/plotting_with_ggplot/#making-plots-with-
plotnine-aka-ggplot

http://ggplot.yhathq.com/docs/scale_color_gradient.html

LIBRERIAS SECUNDARIAS

## Descomprimir zip
Import zipfile
archivo=zipfile.Zipfile(‘archivo.zip’)
print(Archivo.namelist()) (ver los documentos de la lista de archivos)
archivo.estractall() (extraer todos los archivos)
archivo.estract(‘example.png’) (extraer uno en específico)
archivo=zipfile.Zipfile(‘nuevo.zip’,’w’) (crear con permisos de escritura)
archivo.write(‘documento.docx’,compress_type=zipfile.ZIP_DEFLATED) (para sobreescribir un archivo)
archivo.close() (cerrar el archivo)

## Mostrar página en jupyter notebook


from IPython.display import HTML
HTML('<iframe src="URL" width="700" height="400"></iframe>')

GOOGLE COLAB
## Comandos Linux útiles
! ls –l (ver lista de archivos)
! git clone enlace_git (clonar repositorios)
%cd (acceder a otras archivas)
!apt-get install X (para instalar algo)
!pip install X
## Escoger runtime
Runtime – change runtime type - GPU

## Para importar archivos de drive


from drive.colab import drive
drive.mount(‘/content/gdrive’)

## Leer datos
Ruta = ‘ruta/drive’

## Subir y bajar archivos


from google.colab import files
files.upload()
files.download(‘ruta_en_que_estamos’)

COSAS BÁSICAS GIT

Es un sistema de control de versiones, un software que permite registrar el historial de cambios de un proyecto

Repositorio: un proyecto que esta siendo seguido con git, o sea tiene un historial
Rama principal (MASTER): es la que sale al publico
Ramas: con bifurcaciones de la rama principal, que después puede integrarse a la rama principal (Fusión – Marge)
Clon: es un proyecto diferente que se crea a partir de otro

## Flujo de trabajo
git init (crear desde 0)
git clone (clonar)
git status (ver el contenido del git y los cambios)
git add (mandar al Stagin Area ’area de espera’)
git commit -m “mensaje” (mando los cambios al repositorio)
git push (enviar al repositorio en línea)

CMD WINDOWNS

## Ejecutar en segundo plano


>jupyter notebook &

COMANDOS BÁSICOS PARA ESCRIBIR EN HTML

Negrita: <B>…</B>
Cursiva: <I>…</I>
Subrayado: <U>…</U>
Teletipo: <TT>…</TT>
Tachado: <STRIKE>…</STRIKE>
Grande: <BIG>…</BIG>
Pequeña: <SMALL>…</SMALL>
Superíndice: <SUP>…</SUP>
Subíndice: <SUB>…</SUB>

<strong>Este texto va en negritas.</strong>


<div style="text-align: center"> Centrar </div>]

<html> está al inicio de un documento HTML


<head> es la etiqueta que se utiliza para el encabezado de la página
<title> es la etiqueta que da a tu sitio un nombre
<h1>subtitulo1<h1>
<h2> subtitulo2</h2>
<h3> subtitulo3</h3>

Las etiquetas <p> y <br> te ayudarán a organizar el texto en párrafos y saltos de línea
<p>Tu segundo párrafo.</p>
<br> # genera espacio en blanco y un salto de línea
<ol> sirve para agregar listas numeradas y <ul> para agregar bullets
<ul>
<li>Elemento 1</li>
<li>Elemento 2</li>
</ul>

Con el atributo <style> puedes definir el estilo de tu contenido en términos de: Color, Tamaño de fuente, Tipografía
<p style="color:red; font-size:100px">Hola Mundo</p>

Hiperviculo (enlace)
<a href="https//"> texto enlazado </a>

COMANDOS BÁSICOS MARKDOWN

*cursiva*
_cursiva_
**negrita**
__negrita__
***cursiva y negrita***

Hipervínculos
En dicha [web] se recopilo artículos
[web] http://limni.net/blog/

<div class=text-justify> #= pull-left , = pull-right , = centre (otras opciones)


Aqui pon el texto justificado
</div>

COSAS VARIAS

Foro: stackoverflow
plt.ylabel('Ice Extent Northern Hemisphere [km$^2$]') # Poner una letra elevada en titulo

También podría gustarte