#python notebooks
Explore tagged Tumblr posts
ibarrau · 2 years ago
Text
Data Wrangler el método de transformación python similar a PowerBi Query Editor
Hace tiempo que existe una extensión para limpieza de datos en el mercado que no para de llamar la atención. Normalmente me encontré con dos tipos de perfiles que limpian datos, los que aman código (usan python o R) y los que usan herramientas de Bi (power bi, tableau, etc). Creo que esta extensión busca integrar lo mejor de ambos mundos. Utilizar el poder de python con la comodidad visual de las herramientas tradicionales.
Este artículo nos cuenta sobre Data Wrangler. La extensión que permite hacer transformaciones de datos de un archivo de python o jupyter con clicks como si fuera una herramienta de BI.
Para comenzar, veamos la definición de Data Wrangler.
"Es una herramienta de limpieza de datos centrada en código integrada a visual studio code. Apunta a incrementar la productividad de expertos en datos haciendo limpieza al proveer una interfaz que automatiza funciones core de la librería Pandas y muestra útiles insights de las columnas."
Algo así, traducido, es la definición que le dan los creadores. Si bien, al momento de crear este post solo aceptaba Pandas, ya esta disponible el funcionamiento con PySpark Frames.
Para encontrar la herramienta basta con buscarla por VS Code o podes conocer más del proyecto Open Source en su repositorio github. En el mismo encontrarán también opciones de descarga.
Una vez instalado, abrirlo es tan simple como realizar un "head" para un Pandas DataFrame:
Tumblr media
Nos sugiere un botón para iniciar la extensión.
La interfaz nos muestra rapidamente información útil. La veamos por partes:
Tumblr media
Columnas con distribución y estadísticas que nos permiten entenderlas más rapidamente.
Acciones de transformaciones disponibles para ejecutar separadas por categorías
Lista de pasos de transformaciones ejecutados para repasar la historia
Código generado. Esta sección es ideal para aprender más sobre el lenguaje puesto que nos mostrará como es la ejecución de una acción y también nos permitirá modificarla a gusto.
A mano izquierda vemos las transformaciones que podemos elegir seleccionando una columna previamente. Por ejemplo, cambiemos el formato de nuestra columna Order Date. Seleccionamos en las opciones de formato "DateTime formatting example" para mostrarle tal como queremos que sea el formato. Eso nos genera una nueva columna que definiendo el ejemplo se completará y creará luego de darle Apply:
Tumblr media
Si nos ubicamos en el paso anterior podremos ver el código ejecutado como así también modificarlo. Si quisieramos cambiar el nombre de la nueva columna derivedCol por "Fecha de Orden", bastaría con ir al código subrayado donde vemos el nombre y cambiarlo.
NOTA: solo podemos cambiar el código del paso anterior. Los pasos más viejos quedan en preview para evitar sobrecargar la memoria.
Hay operaciones tradicionales de texto como split que simplemente con el delimitador nos ajustaría las columnas
Tumblr media
En caso que conozcamos más sobre el lenguaje también tenemos un espacio para escribir una fórmula de python para una columna nueva o actual. Por ejemplo una operación matemática sencilla:
Tumblr media
Algunos otros ejemplos que estuve probando son reemplazar cadenas de texto, eliminar columnas, agregar columnas por ejemplo y cambiar tipo.
Si en algún momento queremos regresar, tenemos un botón "Back to Notebook" que nos permitiría reordenar código y/o ajustar de manera manual a todo lo que se generó.
Consideremos que si volvemos al notebook, no podremos volver al wrangler tal cual estaba con sus pasos para ver y editar, sino que tendríamos que generar un "head()" nuevo del dataframe del paso de limpieza más reciente para volver a iniciarlo y ejecutar pasos faltantes.
Integración con Fabric
Además del uso local antes mencionado, la herramienta fue integrada con los lanzamientos de Microsoft Build 2023. Notebooks de Fabric no solo pueden ser abiertos en visual studio code para utilizarlo desde allí, sino que tienen una pestaña data que detecta pandas frames para abrir Data Wrangler.
Tumblr media
Así abriremos algo muy similar a lo que vimos en visual studio code
Tumblr media
Si bien se ve idéntica pero en versión clara, tiene algunas diferencias. La integración con Fabric no cuenta con todas las opciones locales como por ejemplo "Create column from formula". No tenemos la opción de escribir el código de una columna. El resto es bastante similar a lo que antes mencionamos.
Conclusión
Esta es una excelente herramienta que puede fortalecer nuestros inicios con Python para mejorar la experiencia de usuario y aprender sobre el código viendo lo que genera finalmente luego de aplicar las operaciones.
Si la comparamos con un editor de consultas de Power Bi se siente algo tosca. De todas formas tiene mucho potencial y oportunidad de crecimiento para ir mejorando.
Una excelente alternativa para quienes no terminan de amigarse con Python y necesitan ejecutar algunas transformaciones entre capas de Lake o ingesta de datos.
0 notes
recurring-polynya · 2 years ago
Text
i just want a lil script that can scrape a spotify playlist and stick all the lyrics into a database that i can do keyword searches on when i need to come up with a title for my fanfic
7 notes · View notes
theresa-of-liechtenstein · 1 year ago
Text
every time i try to put a god damned legend on this graph with seven lines on it my laptop literally freezes for minutes at a time so i can only click one thing before it goes non-responsive again. which is pretty much a great summary of how this stupid capstone project is going.
5 notes · View notes
regsagc · 2 years ago
Text
Tumblr media
Pluto Notebooks is an HTML coding environment that has full Unicode support and gives you the ability to output arbitrary HTML directly into the DOM (including custom CSS styles) and I'm not going to use this power responsibly.
2 notes · View notes
davesanalytics · 4 months ago
Text
Data Cleaning with ChatGPT
0 notes
thesecondface · 5 months ago
Text
third year of the phd and this is the first time i'm implementing functional programming. what have I been DOING until now
1 note · View note
infinetsoft · 8 months ago
Video
youtube
RuntimeError: asyncio.run() cannot be called from a running event loop |...
0 notes
morfanerina · 8 months ago
Text
Every single time I turn on Anaconda (python) on my laptop I just know something will fail. Everyone always enjoys it meanwhile I'm desperately trying to open my conda environment on jupyter notebooks and failing.
I jsut wanted to not use my notes app to do some analysis for once. Please.
1 note · View note
amalgjose · 9 months ago
Text
Python built-in function round() not working in Databricks notebook
This is common issue that developers face while working on pyspark. This issue will happen if you import all functions pyspark. This issue will happen with several other built-in functions in python. There are several functions that shares the same name between the functions in python builtins and pyspark functions. Always be careful while doing the following import from pyspark.sql.functions…
0 notes
gudguy1a · 10 months ago
Text
Anaconda3 Usage - NO.... NO GO THERE!!
A few years back, I attempted to set up Anaconda – ran into all kinds of headaches and pain trying to get that older version up and running. NOTE: Putting this up on one of my sites due to my non-puritan, non-pious language that some of the moderators on those sites do not like…. You know, like using words such as ‘pissed off’ or ‘crappy’…. even though a former Marine Platoon Sergeant, “me” not…
0 notes
jupyter-notebook · 7 days ago
Text
call my software development strategy paradoxical the way i be running cells out of order and loosing track of basic program state
call my software development methodology "evolutionary" the way it takes a billion years and requires the deaths of trillions
1K notes · View notes
ibarrau · 11 months ago
Text
[Fabric] Leer PowerBi data con Notebooks - Semantic Link
El nombre del artículo puede sonar extraño puesto que va en contra del flujo de datos que muchos arquitectos pueden pensar para el desarrollo de soluciones. Sin embargo, las puertas a nuevos modos de conectividad entre herramientas y conjuntos de datos pueden ayudarnos a encontrar nuevos modos que fortalezcan los análisis de datos.
En este post vamos a mostrar dos sencillos modos que tenemos para leer datos de un Power Bi Semantic Model desde un Fabric Notebook con Python y SQL.
¿Qué son los Semantic Links? (vínculo semántico)
Como nos gusta hacer aquí en LaDataWeb, comencemos con un poco de teoría de la fuente directa.
Definición Microsoft: Vínculo semántico es una característica que permite establecer una conexión entre modelos semánticos y Ciencia de datos de Synapse en Microsoft Fabric. El uso del vínculo semántico solo se admite en Microsoft Fabric.
Dicho en criollo, nos facilita la conectividad de datos para simplificar el acceso a información. Si bién Microsoft lo enfoca como una herramienta para Científicos de datos, no veo porque no puede ser usada por cualquier perfil que tenga en mente la resolución de un problema leyendo datos limpios de un modelo semántico.
Tumblr media
El límite será nuestra creatividad para resolver problemas que se nos presenten para responder o construir entorno a la lectura de estos modelos con notebooks que podrían luego volver a almacenarse en Onelake con un nuevo procesamiento enfocado en la solución.
Semantic Links ofrecen conectividad de datos con el ecosistema de Pandas de Python a través de la biblioteca de Python SemPy. SemPy proporciona funcionalidades que incluyen la recuperación de datos de tablas , cálculo de medidas y ejecución de consultas DAX y metadatos.
Para usar la librería primero necesitamos instalarla:
%pip install semantic-link
Lo primero que podríamos hacer es ver los modelos disponibles:
import sempy.fabric as fabric df_datasets = fabric.list_datasets()
Entrando en más detalle, también podemos listar las tablas de un modelo:
df_tables = fabric.list_tables("Nombre Modelo Semantico", include_columns=True)
Cuando ya estemos seguros de lo que necesitamos, podemos leer una tabla puntual:
df_table = fabric.read_table("Nombre Modelo Semantico", "Nombre Tabla")
Esto genera un FabricDataFrame con el cual podemos trabajar libremente.
Nota: FabricDataFrame es la estructura de datos principal de vínculo semántico. Realiza subclases de DataFrame de Pandas y agrega metadatos, como información semántica y linaje
Existen varias funciones que podemos investigar usando la librería. Una de las favoritas es la que nos permite entender las relaciones entre tablas. Podemos obtenerlas y luego usar otro apartado de la librería para plotearlo:
from sempy.relationships import plot_relationship_metadata relationships = fabric.list_relationships("Nombre Modelo Semantico") plot_relationship_metadata(relationships)
Un ejemplo de la respuesta:
Tumblr media
Conector Nativo Semantic Link Spark
Adicional a la librería de Python para trabajar con Pandas, la característica nos trae un conector nativo para usar con Spark. El mismo permite a los usuarios de Spark acceder a las tablas y medidas de Power BI. El conector es independiente del lenguaje y admite PySpark, Spark SQL, R y Scala. Veamos lo simple que es usarlo:
spark.conf.set("spark.sql.catalog.pbi", "com.microsoft.azure.synapse.ml.powerbi.PowerBICatalog")
Basta con especificar esa línea para pronto nutrirnos de clásico SQL. Listamos tablas de un modelo:
%%sql SHOW TABLES FROM pbi.`Nombre Modelo Semantico`
Consulta a una tabla puntual:
%%sql SELECT * FROM pbi.`Nombre Modelo Semantico`.NombreTabla
Así de simple podemos ejecutar SparkSQL para consultar el modelo. En este caso es importante la participación del caracter " ` " comilla invertida que nos ayuda a leer espacios y otros caracteres.
Exploración con DAX
Como un tercer modo de lectura de datos incorporaron la lectura basada en DAX. Esta puede ayudarnos de distintas maneras, por ejemplo guardando en nuestro FabricDataFrame el resultado de una consulta:
df_dax = fabric.evaluate_dax( "Nombre Modelo Semantico", """ EVALUATE SUMMARIZECOLUMNS( 'State'[Region], 'Calendar'[Year], 'Calendar'[Month], "Total Revenue" , CALCULATE([Total Revenue] ) ) """ )
Otra manera es utilizando DAX puramente para consultar al igual que lo haríamos con SQL. Para ello, Fabric incorporó una nueva y poderosa etiqueta que lo facilita. Delimitación de celdas tipo "%%dax":
%%dax "Nombre Modelo Semantico" -w "Area de Trabajo" EVALUATE SUMMARIZECOLUMNS( 'State'[Region], 'Calendar'[Year], 'Calendar'[Month], "Total Revenue" , CALCULATE([Total Revenue] ) )
Hasta aquí llegamos con esos tres modos de leer datos de un Power Bi Semantic Model utilizando Fabric Notebooks. Espero que esto les revuelva la cabeza para redescubrir soluciones a problemas con un nuevo enfoque.
0 notes
sixeyesonathiel · 1 month ago
Text
yearning nerdjo x shy reader, fluff & humor.
a/n: this is so embarrassing bc this is literally how miserable i am irl.
Tumblr media
satoru is down so bad it’s starting to rot his brain. like. visibly. tangibly. his leg’s bouncing under the desk like it’s on fast-forward, the heel of his sneaker thudding rhythmically against the floor tile like a metronome set to desperation. his fingers are drumming nonsense rhythms onto his scratched-up laptop case like he’s trying to decode the algorithm of your absence—tap-tap-tap, pause, tap-tap, like morse code for where is she. his eyes—red-rimmed behind silver-rimmed glasses with one slightly crooked arm—keep flicking to the lab’s entrance like he expects you to materialize in a puff of soft pink mist.
his hoodie’s three days old, and it shows: the sleeves stretched from him pulling them over his hands, the fabric bunched at the elbows. his white t-shirt underneath has a tiny ketchup stain from wednesday’s lunch. the keychain you gave him—blue enamel cat, chipped at the ear—dangles off his pencil pouch like a beacon. his code’s running fine. tabs are hyper-organized. debugging queue nonexistent. he even fixed suguru’s late-night python spiral that nearly bricked the department printer and summoned the wrath of the IT gods.
but it doesn’t matter. because you’re not here.
he’s been looking. he’s always looking.
in the hallway, in the cafeteria, in the reflection of vending machine glass. he leans his stupid giraffe neck around corners like he’s expecting a spontaneous reveal. he scopes out lecture halls he’s not even enrolled in, notebook in hand just in case. every time he hears the soft shuffle of flats in the distance, his head snaps toward it like a bloodhound. he’s started recognizing the rhythm of your steps versus every other pair on campus. your soft-soled shoes tap lighter. more deliberate. his ears practically perk up when he hears a backpack zipper. once he dropped his pen and nearly dislocated his neck looking up, thinking it was you.
and every time it’s not you, his expression glitches—eyes dimming, mouth tightening like his soul just flatlined. it's pathetic. it's art.
he sits sideways in group study like he’s waiting for you to pass by the window. laptop askew. chair half-turned. a ridiculous image—this lanky nerd in a grey hoodie and cargo pants with one pant leg caught in his sock, white wires tangled in his ears and dark under-eyes that make him look like he’s been stress-coding in a cave. (he hasn’t slept. not really. he keeps replaying the way you laughed that one time you dropped your highlighter. it echoes like holy scripture.)
his glasses are smudged. he keeps adjusting them, even when they’re fine. his knuckles are red from resting his chin on them too hard. he keeps fidgeting with your keychain when he’s not typing. thumb brushing over the worn metal, like he’s afraid it’ll disappear if he doesn’t keep touching it. a nervous tic disguised as reverence.
“dude,” suguru says, from two monitors over, voice dry, hair tied up in a lazy half-bun. “you haven’t scrolled in thirty minutes.”
suguru’s slouched in his chair, hoodie sleeves rolled to the elbows, rings tapping against his thermos. his screen's frozen on a meme. he hasn’t blinked in five minutes.
“maybe she’ll walk by,” satoru murmurs, eyes locked on the frosted glass wall outside the lab, hunched forward with his chin on his palm, as if willing your silhouette into existence.
“you said that an hour ago.”
“maybe she’s shy today. maybe she’s building up the courage. maybe she dropped her student ID and fate’s guiding her back here. what if the universe is lining up our pixels right now, suguru? what if—”
“she’s shy every day.”
“and that’s what makes it beautiful,” satoru sighs, dreamily. he stares out the window like a man in a tragic romance film. “she’s mysterious. like a foggy horizon at sea. you don’t know what she’s thinking, and that’s the best part. she could be plotting world domination. she could be drawing cats in the margins of her notes. it’s art.”
suguru groans into his hoodie sleeve.
and then like a glitch in the matrix. like god reached down and clicked “unmute” on the simulation—you pass by.
no footsteps. no warning. just a blur of your jacket sleeve on his left peripheral, and he flinches so hard he nearly spills his water bottle. the water sloshes. he slaps the bottle upright. you’re so close. the scent of your shampoo—jasmine and something warm, like vanilla and late-night bookstores—floods his senses. his head whips around before he can even think, pupils blown wide behind his crooked glasses, mouth parted like a cartoon character seeing a pie on a windowsill.
your gaze meets his.
not one second.
two.
wide eyes. startled. curious. the slope of your brows twitch upward slightly, and your lashes flutter—a beat too long, like a reflex or a stutter in time. your lips part just slightly, like you meant to say something—but don’t. your fingers tug at your sleeve, pulling it over your knuckles in that way you always do when you’re flustered. a half-step pause. your mouth twitches, just barely, like you might’ve smiled. then your gaze drops, your shoulders stiffening as your pace quickens, like you’re embarrassed to have looked at all. your fingers curl tighter around your binder. there’s a sticker on it he hadn’t noticed before.
and that’s it. you’re gone.
satoru slaps both hands over his face and releases a sound that is one part gasp, one part squeal, one part glitching modem.
“oh my god,” he whispers. “oh my god, she looked at me. TWO SECONDS, suguru. TWO. that’s statistically significant. that’s a scientific breakthrough. that’s… that’s eye contact with depth. it had nuance. it had arcs.”
“you’re not well.”
“no, listen. the way her eyes flickered? like she wasn’t sure if she should look away or say something? and her lashes twitched, just a bit. like she was nervous. did you see her hand? she pulled her sleeve down. she only does that when she’s flustered. i know. i’ve studied her. i’ve got timestamps. i’ve got spreadsheets.”
“you’re insane.”
“i’m in love.”
satoru slumps in his chair, limbs sprawling dramatically, glasses askew. he exhales like he’s just seen god. his knee knocks into the desk. his sock has a hole in the toe. the corner of his laptop screen catches the light and reflects a faint shimmer onto the ceiling, and it feels, to him, like stars. his fingers are still frozen mid-air, clutching the keychain like it’s the only proof the moment happened.
“i’m gonna marry her,” he says. “drop out, become a florist. i’ll propose with baby’s breath and carnations—those are her favorites, don’t ask me how i know. maybe a little lavender tucked in. something gentle. delicate. a bouquet that says ‘i know your soul.’”
“you need help.”
“i’ve named our cats already. ichigo, milky, and toblerone. toblerone’s the shy one. milky’s chaotic evil. ichigo wears a little red bow tie. we’ll live in a little flat above a cafe and drink lavender lattes. she’ll wear soft sweaters. she’ll draw comics on sticky notes. i’ll iron her lab coat. it'll be perfect.”
“she doesn’t even know your name.”
“wrong,” satoru says smugly, lifting a single finger like he’s presenting hard evidence. “she knows me as the guy who always looks left and right like a cracked-out meerkat. that’s recognition. that’s brand awareness.”
“romantic.”
“don’t be jealous just ‘cause she didn’t look at you.”
“she’s cute, i guess.”
“NO.” satoru jolts upright like he’s been electrocuted. “DON’T even THINK about perceiving her. your eyes? shut them. your brain? turn it off. opinions? delete them. she’s too good for this world. if anyone’s going to romanticize her, it’s me. with accuracy. and passion. and nuance. only i’m allowed to think she’s cute. and i do. constantly. it’s my full-time job.”
“fine, jeez.”
“say she’s ugly, then.”
“what?? no??”
“exactly. you can’t. because she’s perfect. ethereal. a goddess walking among midterms and overpriced coffee. and she blinked slow, too, did you notice? it was like… like a signal. maybe morse code. she’s trying to tell me something. she’s reaching out. spiritually. through kinetic energy and eye twitches.”
suguru closes his laptop with the tired resolve of someone preparing for battle.
satoru, still glowing with delusion, goes back to staring at the glass wall, head tilted, a soft smile tugging at his lips.
“she looked left,” he murmurs. “that’s my side. she always looks left.”
he swears his hoodie still smells like you.
Tumblr media
2K notes · View notes
tsubakicraft · 2 years ago
Text
せっかく買った本なので
AI系の解説書をいくつか買ったので勉強がてら簡単な文章生成AIを作って仕組みを理解しようと思います。以前にも画像分類や物体検知に関するものを読んでわかったような気になっていましたが、今度はわかった気のレベルを超えたいと思います。 難しい本を読んでいると眠くなるのでなかなか先に進まないです。 Pythonもおぼつかない。 老眼もきつい。 ですが、モノづくり塾で取り組むテーマの一つでもあるので知らないでは済まされません。 昨日からJupyter Notebookを使ってTorchを動かしながら勉強しています。一週間くらい続けて何か成果が出たら良いかな。 モノづくり塾には当面は一人で専有するちょっと大きなGPUを載せた速いPCを置くのが精一杯なので塾に来ないと学習できませんが、いずれはGPUサーバーを置いて塾生がVPNで塾のネットワークに繋げば自宅で学習ができるようにしたい。
Tumblr media
View On WordPress
0 notes
misskamelie · 2 years ago
Text
Coding is the world's funniest activity, actually (person who is currently not having particularly difficult problems)
1 note · View note
emasters · 2 years ago
Text
Configuring Jupyter Notebook in Windows Subsystem Linux (WSL2) | by Cristian Saavedra Desmoineaux | Towards Data Science
Here’s a great quick start guide to getting Jupyter Notebook and Lab up and running with the Miniconda environment in WSL2 running Ubuntu. When you’re finished walking through the steps you’ll have a great data science space up and running on your Windows machine. I am going to explain how to configure Windows 10 and Miniconda to work with Notebooks using WSL2 Source: Configuring Jupyter…
Tumblr media
View On WordPress
0 notes