Jupyter Notebook¶
- ¿Qué es?
- Instalación
- Formas de utilización
- Algunas funcionalidades
- Exportar
En la guía subida al portal encontrarán algunas consideraciones generales para tener en cuenta.
¿Qué es?¶
- Es una herramienta flexible y dinámica que permite la ejecución de código simple a modo de guía y visualización.
- permite ejecutar código python y otros lenguajes.
- cada celda tiene la posibilidad de configurarse para código ejecutable o markdown.
- la ejecución es lineal y las variables se guardan a lo largo de todo el notebook.
- pueden encontrar repositorios de proyectos en github que ponen notebook con ejemplos para ejecutar y probar.
- la utilización de widgets permite agregar funcionalidades al notebook
Formas de utilizarlo¶
Local¶
- al instalarlo poder ejecutarlo desde una terminal
$jupyter notebook
- se inicia en un navegador web
- podes crear, modificar archivos, carpetas, exportar desde donde ejecutas la orden
Remoto¶
- utilizando un servidor instalado y con cuenta creada.
- google-colab es una opción de acceso online y compartido, soporta gran cantidad de librerías además de python, hay que verificar las versiones que se usan.
- conectar el repositorio de código público con binder
Algunas funcionalidades¶
- Atajos:
- Ejecutar una celda y pasara la siguiente → Shift + Enter
- Ejecutar una celda y permanecer en la misma → Ctrl + Enter
- Ejecutar una celda y crear una nueva -> Alt + Enter
- Salir del modo edición para pasar al modo selección → Escape
- Salir del modo selección para entrar al modo edición → Enter
- Agregar una celda debajo de la actual → modo selección + ”b”
- Agregar una celda arriba de la actual → modo selección + ”a”
- Convertir una celda de código a markdown → modo selección + ”m”
In [ ]:
Copied!
?
?
- Instalando librerías
In [ ]:
Copied!
pip install pandas
pip install pandas
- Usando código de lenguajes en celdas markdown:
$pip install pandas
print(f'hola')
- Comandos especiales - magic
In [ ]:
Copied!
%timeit L = [n ** 2 for n in range (1000) ]
%timeit L = [n ** 2 for n in range (1000) ]
In [ ]:
Copied!
%%timeit
L = []
for n in range (1000) :
L.append (n ** 2)
%%timeit
L = []
for n in range (1000) :
L.append (n ** 2)
Comparación eficiencia entre map y for¶
In [ ]:
Copied!
%%timeit
lista = [1,2,3,4,5,6,7,8,9]
lista_dupl = []
for cada in lista:
lista_dupl.append(cada*2)
lista_dupl
%%timeit
lista = [1,2,3,4,5,6,7,8,9]
lista_dupl = []
for cada in lista:
lista_dupl.append(cada*2)
lista_dupl
In [ ]:
Copied!
lista = [1,2,3,4,5,6,7,8,9]
%timeit lista_map_dupl = map(lambda x:x*2, lista)
lista = [1,2,3,4,5,6,7,8,9]
%timeit lista_map_dupl = map(lambda x:x*2, lista)
In [ ]:
Copied!
def dupl(x):
return x*2
%timeit lista_map_dupl = map(dupl, lista)
def dupl(x):
return x*2
%timeit lista_map_dupl = map(dupl, lista)
In [ ]:
Copied!
list(lista_map_dupl)
list(lista_map_dupl)
In [ ]:
Copied!
%timeit L = [n * 2 for n in lista ]
%timeit L = [n * 2 for n in lista ]
- El formato de las celdas de markdown está definido por las características del mismo:
- Agregar imágenes
- listas
- links
- videos
- No es necesario realizar un print para ver el contenido de una variable
In [ ]:
Copied!
lista
lista
In [ ]:
Copied!
texto = ''' NumPy is the fundamental package needed for scientific computing with Python.
Website: https://www.numpy.org
Documentation: https://numpy.org/doc
Mailing list: https://mail.python.org/mailman/listinfo/numpy-discussion
Source code: https://github.com/numpy/numpy
Contributing: https://www.numpy.org/devdocs/dev/index.html
Bug reports: https://github.com/numpy/numpy/issues
Report a security vulnerability: https://tidelift.com/docs/security
It provides:
a powerful N-dimensional array object
sophisticated (broadcasting) functions
tools for integrating C/C++ and Fortran code
useful linear algebra, Fourier transform, and random number capabilities
Testing:
NumPy versions ≥ 1.15 require pytest
NumPy versions < 1.15 require nose
Tests can then be run after installation with:
python -c 'import numpy; numpy.test()'
Call for Contributions
The NumPy project welcomes your expertise and enthusiasm!
Small improvements or fixes are always appreciated; issues labeled as "good first issue" may be a good starting point. If you are considering larger contributions to the source code, please contact us through the mailing list first.
Writing code isn’t the only way to contribute to NumPy. You can also:
review pull requests
triage issues
develop tutorials, presentations, and other educational materials
maintain and improve our website
develop graphic design for our brand assets and promotional materials
translate website content
help with outreach and onboard new contributors
write grant proposals and help with other fundraising efforts
If you’re unsure where to start or how your skills fit in, reach out! You can ask on the mailing list or here, on GitHub, by opening a new issue or leaving a comment on a relevant issue that is already open.
Our preferred channels of communication are all public, but if you’d like to speak to us in private first, contact our community coordinators at numpy-team@googlegroups.com or on Slack (write numpy-team@googlegroups.com for an invite).
We also have a biweekly community call, details of which are announced on the mailing list. You are very welcome to join.
If you are new to contributing to open source, this guide helps explain why, what, and how to successfully get involved.
Powered by NumFOCUS
About
The fundamental package for scientific computing with Python.
numpy.org
Topics
python numpy
Resources
Readme
License
BSD-3-Clause License
Releases 183
v1.20.1 Latest
on 7 Feb
+ 182 releases
Sponsor this project
@numfocus
numfocus NumFOCUS
tidelift tidelift.com/funding/github/pypi/numpy
https://numpy.org/about/
Learn more about GitHub Sponsors
Packages
No packages published
Used by 617k
@sktatsuno
@Andy-CH-BO-AN
@sinablk
@bartmch
@dydwkd486
@mochibbb
@ishujais
@khoa-luan
+ 617,044
Contributors 1,083
@charris
@teoliphant
@mattip
@cournape
@eric-wieser
@seberg
@pearu
@rgommers
@pv
@juliantaylor
@mwiebe
+ 1,072 contributors
Languages
Python 63.4%
C 35.3%
C++ 1.0%
JavaScript 0.1%
Fortran 0.1%
Shell 0.1%'''
texto.split(' ')
texto = ''' NumPy is the fundamental package needed for scientific computing with Python.
Website: https://www.numpy.org
Documentation: https://numpy.org/doc
Mailing list: https://mail.python.org/mailman/listinfo/numpy-discussion
Source code: https://github.com/numpy/numpy
Contributing: https://www.numpy.org/devdocs/dev/index.html
Bug reports: https://github.com/numpy/numpy/issues
Report a security vulnerability: https://tidelift.com/docs/security
It provides:
a powerful N-dimensional array object
sophisticated (broadcasting) functions
tools for integrating C/C++ and Fortran code
useful linear algebra, Fourier transform, and random number capabilities
Testing:
NumPy versions ≥ 1.15 require pytest
NumPy versions < 1.15 require nose
Tests can then be run after installation with:
python -c 'import numpy; numpy.test()'
Call for Contributions
The NumPy project welcomes your expertise and enthusiasm!
Small improvements or fixes are always appreciated; issues labeled as "good first issue" may be a good starting point. If you are considering larger contributions to the source code, please contact us through the mailing list first.
Writing code isn’t the only way to contribute to NumPy. You can also:
review pull requests
triage issues
develop tutorials, presentations, and other educational materials
maintain and improve our website
develop graphic design for our brand assets and promotional materials
translate website content
help with outreach and onboard new contributors
write grant proposals and help with other fundraising efforts
If you’re unsure where to start or how your skills fit in, reach out! You can ask on the mailing list or here, on GitHub, by opening a new issue or leaving a comment on a relevant issue that is already open.
Our preferred channels of communication are all public, but if you’d like to speak to us in private first, contact our community coordinators at numpy-team@googlegroups.com or on Slack (write numpy-team@googlegroups.com for an invite).
We also have a biweekly community call, details of which are announced on the mailing list. You are very welcome to join.
If you are new to contributing to open source, this guide helps explain why, what, and how to successfully get involved.
Powered by NumFOCUS
About
The fundamental package for scientific computing with Python.
numpy.org
Topics
python numpy
Resources
Readme
License
BSD-3-Clause License
Releases 183
v1.20.1 Latest
on 7 Feb
+ 182 releases
Sponsor this project
@numfocus
numfocus NumFOCUS
tidelift tidelift.com/funding/github/pypi/numpy
https://numpy.org/about/
Learn more about GitHub Sponsors
Packages
No packages published
Used by 617k
@sktatsuno
@Andy-CH-BO-AN
@sinablk
@bartmch
@dydwkd486
@mochibbb
@ishujais
@khoa-luan
+ 617,044
Contributors 1,083
@charris
@teoliphant
@mattip
@cournape
@eric-wieser
@seberg
@pearu
@rgommers
@pv
@juliantaylor
@mwiebe
+ 1,072 contributors
Languages
Python 63.4%
C 35.3%
C++ 1.0%
JavaScript 0.1%
Fortran 0.1%
Shell 0.1%'''
texto.split(' ')
In [ ]:
Copied!
texto_mod = texto.split('\n')
texto_mod
texto_mod = texto.split('\n')
texto_mod
- Modificar varias líneas en forma simultánea
In [ ]:
Copied!
person = {"name": "María", "age": 50}
print(f"Nombre: person.get("name")')
print(f"Edad: person.get("age", 20)')
print(f"Dirección: person.get("address")')
print(f"Email: person.get("email", "defaul@email.com")')
print(f"Otra forma de obtener el nombe: person["name"]')
person = {"name": "María", "age": 50}
print(f"Nombre: person.get("name")')
print(f"Edad: person.get("age", 20)')
print(f"Dirección: person.get("address")')
print(f"Email: person.get("email", "defaul@email.com")')
print(f"Otra forma de obtener el nombe: person["name"]')
Ejemplo con algunas funciones vistas¶
Dado un string que contiene datos de los puntajes de un juego, realice un programa que permita obtener los puntajes ordenados según el nivel que se desee
In [ ]:
Copied!
puntajes_nivel ='''maria: 160, uno
Ailen: 45, uno
Ana: 154, dos
Dolores: 186, tres
Inti: 185, dos
Iona: 181, dos
Jimena: 162, tres
Laura: 86, uno
Ludmila: 23, uno
Luján: 117, dos
Celina: 47, dos
Mariana: 174, tres
Mercedes: 152 tres'''
puntajes_nivel ='''maria: 160, uno
Ailen: 45, uno
Ana: 154, dos
Dolores: 186, tres
Inti: 185, dos
Iona: 181, dos
Jimena: 162, tres
Laura: 86, uno
Ludmila: 23, uno
Luján: 117, dos
Celina: 47, dos
Mariana: 174, tres
Mercedes: 152 tres'''
¿Cómo separamos el string?
In [ ]:
Copied!
pn = puntajes_nivel.split('\n')
pn = puntajes_nivel.split('\n')
In [ ]:
Copied!
pn
pn
- Generamos una estructura que permita acceder más facilmente
In [ ]:
Copied!
datos ={}
for linea in pn:
nom, punt, nivel = linea.split()
print(nom.split(':')[0])
print(punt.split(',')[0].strip())
print(nivel.strip())
datos ={}
for linea in pn:
nom, punt, nivel = linea.split()
print(nom.split(':')[0])
print(punt.split(',')[0].strip())
print(nivel.strip())
In [ ]:
Copied!
datos ={}
for linea in pn:
nom, punt, nivel = linea.split()
datos[nom.split(':')[0]] = {'puntaje': int(punt.split(',')[0].strip()), 'nivel':nivel.strip()}
datos
datos ={}
for linea in pn:
nom, punt, nivel = linea.split()
datos[nom.split(':')[0]] = {'puntaje': int(punt.split(',')[0].strip()), 'nivel':nivel.strip()}
datos
- ¿Cómo podemos ordenar nuestros datos?
Ordenar las keys
In [ ]:
Copied!
sorted(datos)
sorted(datos)
- Ordenar por puntaje
In [ ]:
Copied!
datos.keys()
datos.keys()
In [ ]:
Copied!
datos.values()
datos.values()
In [ ]:
Copied!
datos.items()
datos.items()
In [ ]:
Copied!
sorted(datos.items(), key= lambda x:x[1]['puntaje'])
sorted(datos.items(), key= lambda x:x[1]['puntaje'])
- Ordenar por nivel
In [ ]:
Copied!
sorted(datos.items(), key= lambda x:x[1]['nivel'])
sorted(datos.items(), key= lambda x:x[1]['nivel'])
- Obtener los del nivel "uno"
In [ ]:
Copied!
nivel_uno = list(filter(lambda x:x[1]['nivel'] =='uno', datos.items()))
nivel_uno = list(filter(lambda x:x[1]['nivel'] =='uno', datos.items()))
In [ ]:
Copied!
nivel_uno
nivel_uno
In [ ]:
Copied!
def por_nivel(dat, n):
return list(filter(lambda x:x[1]['nivel'] ==n, datos.items()))
nivel_ingre = input('ingrese el nivel: (uno, dos,tres)')
while not nivel_ingre=='':
print(por_nivel(datos, nivel_ingre))
nivel_ingre = input('ingrese el nivel: (uno, dos,tres)')
def por_nivel(dat, n):
return list(filter(lambda x:x[1]['nivel'] ==n, datos.items()))
nivel_ingre = input('ingrese el nivel: (uno, dos,tres)')
while not nivel_ingre=='':
print(por_nivel(datos, nivel_ingre))
nivel_ingre = input('ingrese el nivel: (uno, dos,tres)')
Ejemplo pattern matching¶
In [ ]:
Copied!
numero = int(input("Ingrese un número: "))
match numero:
case 1:
print("Uno")
case 2:
print("Dos")
case _:
print("Otra cosa")
numero = int(input("Ingrese un número: "))
match numero:
case 1:
print("Uno")
case 2:
print("Dos")
case _:
print("Otra cosa")
In [ ]:
Copied!
def avanzar(distancia):
print(f"Robot avanza {distancia} cm")
def girar(grados):
print(f"Robot gira {grados} grados")
def frenar():
print("Robot frena")
def avanzar(distancia):
print(f"Robot avanza {distancia} cm")
def girar(grados):
print(f"Robot gira {grados} grados")
def frenar():
print("Robot frena")
In [ ]:
Copied!
while True:
orden = input("Comando: ").split()
match orden:
case ["avanzar", distancia]:
avanzar(int(distancia))
case ["girar", grados]:
girar(float(grados))
case ["frenar"]:
frenar()
case ["salir"]:
break
case otracosa:
print(f"No entiendo el comando: {otracosa}")
while True:
orden = input("Comando: ").split()
match orden:
case ["avanzar", distancia]:
avanzar(int(distancia))
case ["girar", grados]:
girar(float(grados))
case ["frenar"]:
frenar()
case ["salir"]:
break
case otracosa:
print(f"No entiendo el comando: {otracosa}")
In [43]:
Copied!
patrones= [True, False, [], None, 0]
for i in patrones:
if i == True:
print(f'encontre True')
else:
print(f'encontre False')
patrones= [True, False, [], None, 0]
for i in patrones:
if i == True:
print(f'encontre True')
else:
print(f'encontre False')
encontre True encontre False encontre False encontre False encontre False
In [44]:
Copied!
patrones= [True, False, [], None, 0]
for i in patrones:
match i:
case True:
print(f'encontre True')
case False:
print(f'encontre False')
case _:
print(f'otra cosa')
patrones= [True, False, [], None, 0]
for i in patrones:
match i:
case True:
print(f'encontre True')
case False:
print(f'encontre False')
case _:
print(f'otra cosa')
encontre True encontre False otra cosa otra cosa otra cosa
In [ ]:
Copied!
list(range(2,20,4))
list(range(2,20,4))
Ejemplos de Daniel Moisset, video contando un poco más.
Si quisiera encontrar los números entre 1 y 100 que son múltiplos de 3 y 5, solo de 3, solo de 5 o de ninguno, ¿cómo haríamos?
In [ ]:
Copied!
for i in range(1, 101):
if (i % 3 == 0 ) and (i % 5 == 0):
print("ehh sii")
elif (i % 3 == 0 ):
print("ehh")
elif (i % 5 == 0):
print("sii")
else:
print(i)
for i in range(1, 101):
if (i % 3 == 0 ) and (i % 5 == 0):
print("ehh sii")
elif (i % 3 == 0 ):
print("ehh")
elif (i % 5 == 0):
print("sii")
else:
print(i)
In [ ]:
Copied!
for i in range(1, 101):
match (i % 3 == 0 ), (i % 5 == 0):
case True, True: print("ehh sii")
case True, _: print("ehh")
case _, True: print("sii")
case _: print(i)
for i in range(1, 101):
match (i % 3 == 0 ), (i % 5 == 0):
case True, True: print("ehh sii")
case True, _: print("ehh")
case _, True: print("sii")
case _: print(i)
In [ ]:
Copied!
points = [(0, 0), (0,5), (5,0), (5,5), ('f',8), ('f')]
for point in points:
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
points = [(0, 0), (0,5), (5,0), (5,5), ('f',8), ('f')]
for point in points:
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
In [ ]:
Copied!