← Back to list

10 Snippets to Make Your Code More Elegant

Try these codes if you want to make your Python code cleaner and more readable.

Gustavo R Santos in Code Applied · 2026-06-07 18:25 · 11 claps · 4.5 min read paywalled
#python #python-programming #data-science #pandas #data-analysis
Open on Medium ↗
Wiki topics: ML · Machine Learning 💻 · Programming 🔬 · Science · General 🐾 · Pets & Animals

10 Snippets to Make Your Code More Elegant

Try these codes if you want to make your Python code cleaner and more readable.

Organizing the code | Image generated by AI. Google Gemini, 2026. https://gemini.google.com

Organizing the code | Image generated by AI. Google Gemini, 2026. https://gemini.google.com

I usually work with Python in my daily job. Writing relevant and organized code is a must for a few reasons. Among those reasons:

  • You will have to understand what you did in the future. Think about you.
  • If you move on to another job or company, someone will have to maintain your code someday. Think about the others.

With that in mind, in the next few code snippets, I think we can improve our code with just a few touches, saving some time when writing it and when reading it again. That is why I am sharing them with you.

Code Snippets

Let’s get started with the fun part: coding.

The code snippets for each situation are in the sequence.

1. Group by a lot of columns

When we have to group by many columns in Pandas, it is needed to add a pair of quotes for each column name. But this code using str.split() is much faster to write. You can write it once and Copy + Paste as needed.

# Columns to group by
cols_to_groupby = str.split('col1, col2, col3, col4', sep=', ')
"The output of this will be a list ['col1','col2', 'col3', 'col4']"

# The variable cols_to_groupby is used in the groupby function
my_grouped_df = (
    df
    .groupby(cols_to_groupby)
    .agg({ 'col5': 'mean',
           'col6': 'sum'  })
    .reset_index()
)

Bonus Snippet

You can give a name to the grouped columns while you group them, eliminating the need of using methods like .rename() later.

# Columns to group by
cols_to_groupby = str.split('col1, col2, col3, col4', sep=', ')
"The output of this will be a list ['col1','col2', 'col3', 'col4']"

# The variable cols_to_groupby is used in the groupby function
my_grouped_df = (
    df
    .groupby(cols_to_groupby)
    .agg( mean_col5= ('col5', 'mean'),
          sum_col6= ('col6', 'sum') )
    .reset_index()
)

2. Changing columns orders

The same way we used the previous code for grouping, we can use it to reindex columns in a data frame.

df.reindex( columns= str.split('col1, col2, col4, col5, col3', sep=", ") )

3. Changing the data type of many columns at once

If we want to change the data type of a column in Pandas, we can go to astype(). If we’re dealing with a lot of columns, here is a good way to do that.

# Create a dictionary with the name of the column and the data type
data_types = {'col1':'float',
              'col2':'category',
              'col3':'int',
              'col4':'int' }

# Change all at once.
df= df.astype(data_types)

4. Separate column by a text pattern

We can separate one column in two separate columns using the next code.

# Example of data 
        col
0  val1-val2
1  val1-val2
# Use str.split to separate the column  by "-" 
df.col.str.split("-", expand = True)
      0     1
0  val1  val2
1  val1  val2

5. Using Pandas query to slice the data

Slicing data is tremendously useful while exploring datasets. But the slicing notation [row, col] can hold you back sometimes. Using .query() helps us slice data faster and use a query-like language.

# Using query: use the column name and the condition between quotes.
df.query('col_name > 10')
df.query(' col_name == "text" ')

Learn more about Pandas Query in this post.

[embed]Pandas Query: the easiest way to filter data Learn 9 code snippets that will enhance your productivity.medium.com

6. Checking conditions

We can check many conditions at the same time with the built-in functions all() and any().

# Variables
a = 12
b = 1

# Conditions
conditions = [ a > 10,
               b == 0 ]

# a AND b follow the conditions
all(conditions)  ##[OUTPUT]## False

# a OR b follow the conditions
any(conditions)  ##[OUTPUT]## True

7. Pipelines

I am not sure about you, but I find it much more elegant to write the Scikit-Learn pipeline steps separately. It makes the code much more readable and easier to change, too. Here’s how I usually write it.

# Steps
steps = [
  ('scale', StandardScaler()),
  ('model', SVR())
]

# Fit Pipeline
pipe = Pipeline(steps).fit(X,y)

8. Use Pathlib

Using **pathlib **for robust path management.

Instead of using os.path.join and complex string manipulations, pathlib offers an object-oriented approach that is more readable and cross-platform compatible.

from pathlib import Path

# Elegant path joining and existence check
data_path = Path("data") / "processed" / "metrics.csv"
if data_path.exists():
    df = pd.read_csv(data_path)

9. Creating Data Mask

Simplifying conditional data transformations with np.where or mask.

Avoid explicit loops or bulky apply functions for conditional data cleaning in Pandas. Using vectorization makes code significantly faster and more concise.

import numpy as np

# Replace specific conditions across an entire column in one line
df['risk_level'] = np.where(df['score'] > 0.8, 'High', 'Low')

10. Replacing manual dictionary validation with Pydantic

Instead of writing complicated if statements to check if keys exist or if types are correct in an API payload, you can use Pydantic models to enforce structure automatically.

This snippet is “elegant” because it shifts your code from imperative (telling the program how to check for data) to declarative (telling the program what the data should look like).

You define the schema (the shape) of the data upfront using type hints. You are no longer writing code to check the data; you are describing what “correct” looks like, and the library handles the verification automatically.

from pydantic import BaseModel, Field, EmailStr

class UserProfile(BaseModel):
    user_id: int # Define integer ID field
    email: EmailStr  # Enforce email format validation
    is_active: bool = Field(default=True) # Boolean with default True

# This succeeds
data = {"user_id": 123, "email": "dev@example.com"}
profile = UserProfile(**data) # Validate and unpack/parse dictionary

# This raises a ValidationError
bad_data = {"user_id": 123, "email": "not-an-email"}
profile = UserProfile(**bad_data)

Before You Go

Well, these were just a couple of code snippets for you to incorporate into your daily job, making your code a little more elegant (that’s my opinion, at least…).

Feel free to try them out and use as needed. And as I also do with another post I have with code snippets for PySpark, I will try to keep adding more snippets to this post as I remember or create them, so make sure to save it for reference, if you’d like.

If you liked this content, follow Code Applied for more.

[embed]Code Applied Code Applied delivers practical, bite-sized tutorials on data science, AI agents, automation, and more. Each post packs…medium.com

References

[embed]DataFrame - pandas 3.0.3 documentation Constructor Axes Conversion Computations / descriptive stats Missing data handling Combining / comparing / joining /…pandas.pydata.org

[embed]pathlib - Object-oriented filesystem paths Source code: Lib/pathlib/ This module offers classes representing filesystem paths with semantics appropriate for…docs.python.org

[embed]Models One of the primary ways of defining schema in Pydantic is via models. Models are simply classes which inherit from and…pydantic.dev


메타데이터
post_id
2244f5dc83b8
slug
10-snippets-to-make-your-code-more-elegant-2244f5dc83b8
url
https://medium.com/code-applied/10-snippets-to-make-your-code-more-elegant-2244f5dc83b8
canonical_url
https://medium.com/code-applied/10-snippets-to-make-your-code-more-elegant-2244f5dc83b8
author_url
https://medium.com/@gustavorsantos
status
ok
fetched_at
2026-06-11 15:16:29