Discover and read the best of Twitter Threads about #python

Most recents (24)

One of #Python's most controversial built-in functions is `eval()`. The main reason it is controversial is that it can be used to execute arbitrary code.


The arguments for `eval()` are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

Here is an example: Image
You can use `eval()` to evaluate/execute the arbitrary code objects that you get when you run Python's `compile()` function.

The `eval()` built-in is closely related to the `exec()` built-in. `exec()` will take a code block while `eval()` only takes a single expression
Read 4 tweets
Sale hilo de tema interesantísimo que salió hoy de space con @patriciomolina por si se lo perdieron

🧵"Frontera eficiente aplicada a carteras Crypto"

El concepto nace de una alta idea de un tal Harry Markowitz en 1952, dejo link a paper original…
Conceptualmente lo que planteó Markowitz es una forma óptima de diversificar las inversiones para maximizar el retorno vs el riesgo asumido

Para ello necesitamos que el retorno de los componentes sea el mayor posible pero que el riesgo (aka. volatilidad) sea lo menor posible Image
Hasta acá divino, peeero tenemos un problemita..

Lo que pasa es que a mayor retorno esperado => mayor riesgo, como sabe cualquier Degen 😂

Entonces arranca usando estas fómulas para calcular retorno y volatilidad del portafolio dados los "X" (ponderaciones de cada activo) Image
Read 17 tweets
A #Python student showed me this code, and asked how to improve it:

def f(g, **kwargs):
for k, v in kwargs.items():
if "x1" == k:
g.x1 = v
elif "x2" == k:
g.x2 = v
elif "x3" == k:
g.x3 = v
First, what's this function doing?

- It gets an object and a dict of keyword arguments
- It goes through each keyword arg
- For three keys, it creates an attribute of that name on the object (g), with the value.

Let's assume the function can work for *all* keys. What can we do?
Well, we can always assign an attribute to nearly any Python object:

a.b = 100

This adds an attribute "b" to the object "a", with a value of 100 (an int).

We can accomplish the same with the "setattr" builtin:

setattr(a, 'b', 100)

Notice that 'b' is a string here!
Read 8 tweets
Given a #Python list of numeric strings:

x = ['1', '2', '3']

I can try to use "sum(mylist)". But that'll fail, because they're strings. I can use a list comprehension to convert them:

for y in x])

But it also works without the []:

for y in x)

List comprehensions return (by definition) lists. So this:

for y in x]

returns a list -- in this case, a list of ints. The list is returned all at once, though.
To save memory, it's often best to use a generator comprehension:

for y in x)

This doesn't return a list. Rather, it returns a generator, an object that knows how to behave in a "for" loop. You can say:

g = (int(y) for y in x)

for i in g:
print(i) # 1, 2, 3
Read 4 tweets
New release for @Uber forecasting library 🌈

Orbit is an open-source #Python library for Bayesian time series forecasting and inference applications developed by @UberEng 🧵 👇🏼

#timeseries #forecast #MachineLearning #PyTorch #Bayesian #Bayes
The library uses under the hood probabilistic programming languages with libraries such as #Python @mcmc_stan , Pyro, and #PyTorch to build the forecast estimators.

The new release, version 1.1 includes the following new features and changes: 👇🏼
New #forecasting model - Kernel Time-based #Regression (KTR). KTR model uses latent variables to define a smooth, time-varying representation of regression coefficients. Tutorials: 👇🏼…………
Read 8 tweets
How large are the chances of dying from c19 once infected compared with regular mortality?

Quite similar to the regular chances of dying within a year.

Or take it differently: if you get c19 it's roughly equivalent to becoming 10 years older (just in this year)
IFR data collected by @zorinaq
Mortality data @HMDatabase
I know, the way I read the #python object in #rstats must be a 🤦, sorry @ykashnitsky 😅
Read 5 tweets
H2O new release! 🚀🚀🚀

This week, H2O had a major release of their ML open-source library for #R and #Python, introducing two new algorithms, improvements, and bug fixing. ❤️👇🏼 🧵

#MachineLearning #ML #DeepLearning #rstats #DataScience #DataScientists
New algorithm (1/2):
✨ Distributed Uplift Random Forest (Uplift DRF) - The Uplift DRF is a tree-based algorithm that uses a Random Forecast classifier to estimate a treatment's incremental impact. See demo on the notebook ⬇️…
#randomforest #ML #UpLift
New algorithm (2/2):
✨ Infogram & Admissible Machine Learning - is a new tool for machine learning interpretability. More details are available on the algorithm doc ⬇️…
#machinelearning #ML
Read 5 tweets
Argh! Who thought Black should be automatically applied to lines in the IPython CLI?

The makes it less useful for education purposes, less useful for interactive math, and annoying when it rewrites your input across multiple lines.
In a #Python course, if you want to demonstrate that print('hello') and print("hello") are the same, then too bad. The CLI rewrites both to use double quotes and the students can't see what you were demonstrating.
When doing math, you improve readability by grouping your terms as shown in PEP 8:

3*x**2 - 5*x + 10

However, the new #Ipython CLI immediately expands it to:

3 * x ** 2 - 5 * x + 10
Read 12 tweets
Did you know that An Introduction to Statistical Learning (ISLR) book has an online course? 🎥 🌈❤️
@edXOnline is offering an online course by @Stanford University, following the book curriculum: 🧵 👇🏼

#rstats #Statistics #ML #datascience
The course instructors are two of the book authors - Prof. Trevor Hastie and Prof. @robtibshirani. While the book is based on #R some awesome people translate it to #python, #julialang, and other #Rstats flavors (see links on the comments below 👇🏼).
The course covers the following topics (aligned with the book curriculum):
Read 9 tweets
Many #Python beginners are confused by space characters, empty strings, and the term "whitespace." After all, how can nothing be something? (Or: How can something be nothing?)

A thread about nothing!

(Cue the Seinfeld theme, I guess...)

s = 'a b'

This string contains three characters. As humans, we only see the "a" and "b", two characters separated by a space.

But computers don't work that way: The space character is a character. It takes up just as much space in memory as either "a" or "b".
We can see this if we iterate over the characters in s, printing their Unicode numbers:

>>> s = 'a b'
>>> for c in s:
... print(ord(c))
Read 16 tweets
How to Create Small Multiple Charts in Python, with Plotly


#python #datascience #pythoncode #datavisualization

Before I get into the mechanics of how to create a small multiple charts in Python, let me quickly explain why they are so important.

Small multiple charts are one of my favorite chart types.

They are very powerful, and also highly under-used.

#datascience #dataanalytics #datavisualization
Read 23 tweets
Thread 🧵

A compilation of cool and useful ideas to leverage #Python for #SEO purposes. These are just some ideas on how to improve your workflow (automation) or to gather new insights in a smarter way

1. Sitemap analysis: check content velocity and how much content your competitors have per section. You can also look for most common words in their URLs to have a high-level overview of what they post about
2. Broken link checker: pretty basic. Highly suggested when you need a lightweight function and don't want to launch Screaming Frog or other tools.

It's the most basic use in this list!
Read 11 tweets
How to Do a Data Analysis


#datascience #DataAnalytics #Python #rstats

When you do data analysis, you first need to start by clarifying objectives.

Why are you doing the analysis?
What’s the end goal? (e.g., the thing you’re trying to improve, understand, etc)

#datascience #DataAnalytics #data

To do this in a business setting, you’ll typically talk with stakeholders, business partners, and other team members who are familiar with the subject of the analysis.
Read 42 tweets
New book for Bayesian statistics with #Python! 📚📊🚀
The Bayesian Modeling and Computation in Python by
@aloctavodia, @canyon289, and @junpenglao provides an introduction to Bayesian statistics using core Python libraries for Bayesian 🧵 👇🏼

#bayesian #MachineLearning #stats ImageImageImage
The book covers the following four topics:
- Bayesian Inference concepts
- Bayesian regression methods for linear regressions, splines,
- Time series #forecasting
- Bayesian additive regression trees
- Approximate of Bayesian computation
The book's authors are the contributors of PyMC3, ArviZ, Bambi, #TensorFlow Probability, and other #Python libraries:
PyMC3 -
Tensorflow Probability -
ArviZ -
Read 6 tweets
Why You're Very Likely to Become A Millionaire in Data Science or Machine Learning


#datascience #jobs #money #machinelearning

The reasons that you're likely to become a millionaire in data science:

1. salaries are already high in 2021
2. competition for high salaries is weaker than you think
3. salaries are likely to increase in the 2020s

Let's look at each of these.

#datascience #money #jobs

Let's start with current salaries.

According to Kaggle, the median salary for a US Data Scientist in 2021 is close to $200,000.…

#datascience #data #jobs
Read 30 tweets
Let's talk a little about accessing #Python dictionaries!

Most beginners will access a dictionary like this:

What happens if you try to access a key that doesn't exist in a #Python dictionary?

You'll get a KeyError!
There are several different ways to handle a KeyError. 🐍⚠️

You could wrap it in a `try/except`. Another approach is to use the `get()` dictionary method, like this:
Read 6 tweets
Python includes a built-in callable named `bytearray()`.

The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. They return a new array of bytes


A bytearray in #Python takes the following optional arguments:

🐍 source[optional]: Initializes the array of bytes
🐍 encoding[optional]: Encoding of the string
🐍 errors[optional]: Takes action when encoding fails
It is often useful to see an unfamiliar concept in action. Here are two examples of creating a bytearray using different encodings and printing them out Image
Read 5 tweets
Starting in Python 3.7, the `breakpoint()` built-in function was added

It is defined in PEP 553 and simplifies adding a breakpoint to your code


You can read about the `breakpoint()` function for Python here:…
Here is some sample code showing how to use the `breakpoint()` function in your Python code Image
Read 6 tweets
👉 3 Tools to Track and Visualize the Execution of Your Python Code:…

#Python #VisualizationTools #DataScience
1.Loguru:Loguru is a library that aims to make logging in Python enjoyable. Loguru provides many interesting functionalities, but one functionality that is the most helpful is the ability to catch unexpected errors and display which value of a variable causes your code to fail.
2. snoop: snoop is a Python package that prints the lines of code being executed along with the values of each variable by adding only one decorator.
Read 4 tweets
Seen some tweets about #Python lambdas recently.

There are alternatives to lambdas which are still one-liners but are faster and (arguably) simpler.

Let's look at a few.

Let's say you want a quick function to upper class a string.

Here's the obvious lambda solution:

lambda s: s.upper()

But you can also do the following:


Both define a callable that upper cases a string, but the latter is faster.
Let's look at doubling a number. Here's the most obvious lambda:

lambda n: n * 2

Here's an alternative:

2 .__mul__

It's faster, if less readable. Consider it for tight loops.
Read 7 tweets
Bueno pues aqui voy con mi particular acercamiento al snippet de @thinbaker con la librería Pillow.

Claro que como ya adelanté, yo he integrado el código del tocayo en mi herramientilla/playground de python #Python
Ya dije q suelo iterar sobre un concepto en cada oportunidad. Como veis hay un fichero principal y una "carga de pago" consistente en uno o varios comandos como modulos independientes...

En este caso hay tres snippets sacados de Twitter integrados en la misma herramienta..
El modulo main se encarga de preparar la estrutura de argparse, aumentarla con "subparsers" para cada comando que se añada y de comprobar la cmdline y bifurcar al comando apropiado... Es casi lo mismo que visteis para el #AdventOfCode
Read 19 tweets
Regular #python dicts can efficiently emulate methods exclusive to OrderedDict:

# Remove oldest
# od.popitem(0)
>>> d = dict(a=1, b=2, c=3)
>>> del d[next(iter(d))]
>>> d
{'b': 2, 'c': 3}

# Refresh position
# od.move_to_end('b')
>>> d['b'] = d.pop('b')
>>> d
{'c':3, 'b': 2}

These two methods are all you need to efficiently implement your own LRU cache variants:

# Cache miss: Store new entry and remove oldest
d[args] = func(*args)
if len(d) > maxsize:

# Cache hit: Refresh position

Regular dicts already have d.popitem() which does the same as od.popitem(True) for OrderedDicts.

Ordered dicts have an od.move_to_end(key, 0) that moves entries to the beginning. There is no fast, clean equivalent for regular dicts.

Read 3 tweets
2021: A year in review for AWS Lambda Powertools Python 🧵 #Python #Serverless
v1.10.0: Logger, Tracer, Validator, and Parameters

- Parameter: AppConfig support @IsenbergRan
- Logger: Support for extra parameter @heitor_lessa…
v1.10.1 / v1.10.2 / v1.10.3 / v1.10.4 - Bug fixes, code coverage, typing and documentation

- Internal benchmarks @NMoutschen
- Migrate documentation from Gatsby to MkDocs material @am29d
Read 26 tweets

I want to share with you some of the best #Python resources from beginner to advanced.

Please check the thread 👇
1. Courses

Couple of free courses to learn Python from scratch

2. Algorithms and Data structures.

Videos, texts, repositories about algorithms and data structures

Read 8 tweets

Related hashtags

Did Thread Reader help you today?

Support us! We are indie developers!

This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3.00/month or $30.00/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!