Skip to main content

spinesUtils

Accelerate your Python development workflow

Overview

spinesUtils is a powerful library that provides ready-to-use features and utilities for Python development to shorten the project development cycle. Our goal is to help developers focus on solving their core problems instead of reimplementing common functionality.

Features

  • Logging functionality - Simplified logging without handler conflicts
  • Type checking and parameter validation - Robust validation decorators
  • CSV file reading acceleration - Performance-optimized data loading
  • Imbalanced data classifiers - Specialized ML tools for imbalanced datasets
  • Pandas DataFrame data compression - Memory optimization for large datasets
  • DataFrame insight tools - Quick data analysis and visualization
  • Large data train-test splitting - Efficient data partitioning for ML pipelines
  • Intuitive timer - Simple timing and benchmarking tools

This library is currently undergoing rapid iteration. If you encounter any issues with its functionalities, feel free to raise an issue.

Installation

You can install spinesUtils from PyPI:

pip install spinesUtils

Usage Examples

Logger

The Logger class provides convenient logging without worrying about handler conflicts with the native Python logging module.

# load spinesUtils module
from spinesUtils.logging import Logger

# create a logger instance, with name "MyLogger", and no file handler, the default level is "INFO"
# You can specify a file path `fp` during instantiation. If not specified, logs will not be written to a file.
logger = Logger(name="MyLogger", fp=None, level="DEBUG")

logger.log("This is an info log emitted by the log function.", level='INFO')
logger.debug("This is an debug message")
logger.info("This is an info message.")
logger.warning("This is an warning message.")
logger.error("This is an error message.")
logger.critical("This is an critical message.")

Type Checking and Parameter Validation

Ensure your functions receive the correct input types and values:

from spinesUtils.asserts import *

# Check parameter type
@ParameterTypeAssert({
    'a': (int, float),
    'b': (int, float)
})
def add(a, b):
    return a + b

# Check parameter value
@ParameterValuesAssert({
    'a': lambda x: x > 0,
    'b': lambda x: x > 0
})
def divide(a, b):
    return a / b

# Generate function kwargs
params = generate_function_kwargs(add, a=1, b=2)

CSV Reading Acceleration

Read large CSV files efficiently:

from spinesUtils import read_csv

df = read_csv(
    fp='/path/to/your/file.csv',
    sep=',',  # equal to pandas read_csv.sep
    turbo_method='polars',  # use turbo_method to speed up load time
    chunk_size=None,  # it can be integer if you want to use pandas backend
    transform2low_mem=True,  # compresses file to save memory
    verbose=False
)

Classifiers for Imbalanced Data

Handle imbalanced datasets effectively:

from spinesUtils.models import MultiClassBalanceClassifier
from sklearn.ensemble import RandomForestClassifier

classifier = MultiClassBalanceClassifier(
    base_estimator=RandomForestClassifier(n_estimators=100),
    n_classes=3,
    random_state=0,
    verbose=0
)

# Fit and predict as you would with any scikit-learn estimator
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)

DataFrame Data Compression

Optimize memory usage for large DataFrames:

from spinesUtils import transform_dtypes_low_mem

# Compress a single DataFrame
transform_dtypes_low_mem(df, verbose=True, inplace=True)

# Batch compress multiple DataFrames
from spinesUtils import transform_batch_dtypes_low_mem
transform_batch_dtypes_low_mem([df1, df2, df3, df4], verbose=True, inplace=True)

DataFrame Insight Tools

Quickly analyze your data:

from spinesUtils import df_preview, classify_samples_dist

# Get comprehensive DataFrame insights
df_insight = df_preview(df)

Data Splitting Utilities

Efficiently split large datasets:

from spinesUtils import train_test_split_bigdata, train_test_split_bigdata_df
from spinesUtils.feature_tools import get_x_cols

# Return numpy arrays
X_train, X_valid, X_test, y_train, y_valid, y_test = train_test_split_bigdata(
    df=df, 
    x_cols=get_x_cols(df, y_col='target_column'),
    y_col='target_column', 
    shuffle=True,
    return_valid=True,
    train_size=0.8,
    valid_size=0.5
)

# Return pandas DataFrames
train_df, valid_df, test_df = train_test_split_bigdata_df(
    df=df, 
    x_cols=get_x_cols(df, y_col='target_column'),
    y_col='target_column', 
    shuffle=True,
    return_valid=True,
    train_size=0.8,
    valid_size=0.5
)

Timer Utility

Time your code execution simply:

from spinesUtils.timer import Timer

# As a context manager
with Timer().session() as t:
    # Your code here
    t.sleep(1)
    print(f"Step 1 time: {t.last_timestamp_diff():.2f}s")
    
    # Mark a middle point
    t.middle_point()
    
    # More code
    t.sleep(2)
    print(f"Step 2 time: {t.last_timestamp_diff():.2f}s")
    
print(f"Total time: {t.total_elapsed_time():.2f}s")

# Or use it manually
timer = Timer()
timer.start()
# Your code here
timer.end()
print(f"Elapsed: {timer.total_elapsed_time():.2f}s")

Metadata

Release files for spinesUtils 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for spinesUtils 0.5.0
File Size Uploaded
spinesutils-0.5.0.tar.gz 52.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for spinesUtils 0.5.0
File Interpreter ABI Platform
spinesutils-0.5.0-py3-none-any.whl Python 3 none any Details

Total release size: 97.5 kB

Release files / spinesutils-0.5.0.tar.gz

Download URL spinesutils-0.5.0.tar.gz
Size 52.0 kB
Tags Source
SHA-256 checksum
How to use checksums
fa78ae0745ac6b15fc000975f389749228b26b7748d8429e14d0fc4e1debdac7
BLAKE2b-256 checksum
How to use checksums
f1cd2b509391abc0d7be54bff6853dcf6812e9c13937d331fc9d1ed70f404446
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.10

Release files / spinesutils-0.5.0-py3-none-any.whl

Download URL spinesutils-0.5.0-py3-none-any.whl
Size 45.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bff954ec7b4da8cb93e9a4b6db40b11f67cfd8b46b37b37667977cd93240162d
BLAKE2b-256 checksum
How to use checksums
4d7989e9ba5c63181dd47775aa94f9e65e334e532cc95c5dcd718a915e7bccff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.10

Release history Release notifications | RSS feed

This release

0.5.0 This release

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.13

2 release files

0.3.12

2 release files

0.3.11

2 release files

0.3.10

2 release files

0.3.9

2 release files

0.3.8

2 release files

0.3.7

2 release files

0.3.6

2 release files

0.3.5

2 release files

0.3.4

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.8

2 release files

0.2.5

2 release files

0.2.0

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page