A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improve: Add more relevant snippets to the snippets panel (`1/2`) (#3709)
Srihari Thyagarajan70f5a67c41c3
diff --git a/marimo/_snippets/data/altair-10.py b/marimo/_snippets/data/altair-10.pynew file mode 100644index 0000000000..810d0f057f--- /dev/null+++ b/marimo/_snippets/data/altair-10.py@@ -0,0 +1,86 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Visualization: Box Plot with Violin Layer in Altair++ Create layered box and violin plots with Altair. Box plots display quartiles via `mark_boxplot()`+ while violin plots show density distributions using `transform_density()`.+ Combining them reveals both summary statistics and full data distributions in a single visualization.+ """+ )+ return+++def _():+ from vega_datasets import data+ import altair as alt+ return alt, data+++def _(alt, data):+ def create_box_violin_plot():+ # Load the dataset+ source = data.cars()++ # Create the base chart for the box plot+ box_plot = alt.Chart(source).mark_boxplot(size=50).encode( # Increased box size+ x=alt.X('Origin:N', axis=alt.Axis(labelFontSize=12, titleFontSize=14)), # Larger font+ y=alt.Y('Horsepower:Q',+ title='Horsepower',+ scale=alt.Scale(zero=False),+ axis=alt.Axis(labelFontSize=12, titleFontSize=14)), # Larger font+ color=alt.Color('Origin:N', legend=alt.Legend(labelFontSize=12, titleFontSize=14)) # Larger legend+ )++ # Create the violin layer+ violin = alt.Chart(source).transform_density(+ 'Horsepower',+ as_=['Horsepower', 'density'],+ groupby=['Origin']+ ).mark_area(+ opacity=0.3+ ).encode(+ x='Origin:N',+ y='Horsepower:Q',+ color='Origin:N',+ fill='Origin:N'+ )++ # Combine the layers+ chart = (violin + box_plot).properties(+ width=600, # Much larger width+ height=500, # Much larger height+ title={+ 'text': 'Horsepower Distribution by Origin',+ 'fontSize': 16 # Larger title+ }+ ).configure_axis(+ labelFontSize=12,+ titleFontSize=14+ ).interactive()++ return chart++ create_box_violin_plot()+ return (create_box_violin_plot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/altair-11.py b/marimo/_snippets/data/altair-11.pynew file mode 100644index 0000000000..8535ad5956--- /dev/null+++ b/marimo/_snippets/data/altair-11.py@@ -0,0 +1,70 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Visualization: Faceted Charts in Altair++ Faceted charts split your data into multiple views based on categories, making it easy to spot patterns and compare groups.+ Built with Altair's `facet()` method and includes interactive zoom/pan controls via `.interactive()`.+ """+ )+ return+++def _():+ from vega_datasets import data+ import altair as alt+ return alt, data+++def _(alt, data):+ def create_faceted_chart():+ # Load the dataset+ source = data.cars()++ # Create interactive base scatter plot+ base = alt.Chart(source).mark_point().encode(+ x='Horsepower:Q',+ y='Miles_per_Gallon:Q',+ color='Origin:N',+ tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']+ ).properties(+ width=180,+ height=180+ ).interactive() # Make base chart interactive++ # Create faceted chart+ chart = base.facet(+ column='Cylinders:O',+ title='Miles per Gallon vs. Horsepower by # Cylinders'+ ).configure_header(+ labelFontSize=12,+ titleFontSize=14+ ).configure_title(+ fontSize=16+ )++ return chart++ create_faceted_chart()+ return (create_faceted_chart,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/altair-12.py b/marimo/_snippets/data/altair-12.pynew file mode 100644index 0000000000..1cd2f9be1a--- /dev/null+++ b/marimo/_snippets/data/altair-12.py@@ -0,0 +1,66 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Visualization: Area Charts with Gradient Fill++ Create stacked area charts using `alt.Chart().mark_area()`. Demonstrates+ gradient fills and opacity settings with `fillOpacity`. Common for+ visualizing time series data or part-to-whole relationships.+ """+ )+ return+++def _():+ from vega_datasets import data+ import altair as alt+ return alt, data+++def _(alt, data):+ def create_area_chart():+ # Load the dataset+ source = data.stocks()++ # Create area chart with gradient+ chart = alt.Chart(source).transform_filter(+ alt.datum.symbol != 'IBM' # Remove one symbol to avoid overcrowding+ ).mark_area(+ opacity=0.7,+ interpolate='monotone'+ ).encode(+ x='date:T',+ y=alt.Y('price:Q', stack=True),+ color=alt.Color('symbol:N', legend=alt.Legend(title='Company')),+ tooltip=['date', 'price', 'symbol']+ ).properties(+ width=600,+ height=300,+ title='Stock Prices Over Time'+ ).interactive()++ return chart++ create_area_chart()+ return (create_area_chart,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/altair-13.py b/marimo/_snippets/data/altair-13.pynew file mode 100644index 0000000000..3b4bb113c8--- /dev/null+++ b/marimo/_snippets/data/altair-13.py@@ -0,0 +1,66 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Visualization: Distribution Plots in Altair++ Create distribution visualizations using `mark_area()` and `transform_density()`.+ Common for comparing distributions across categories with interactive tooltips.+ """+ )+ return+++def _():+ from vega_datasets import data+ import altair as alt+ return alt, data+++def _(alt, data):+ def create_distribution_plot():+ # Load dataset+ source = data.cars()++ # Create distribution plot+ chart = alt.Chart(source).transform_density(+ 'Miles_per_Gallon',+ groupby=['Origin'],+ as_=['Miles_per_Gallon', 'density']+ ).mark_area(+ opacity=0.5+ ).encode(+ x='Miles_per_Gallon:Q',+ y='density:Q',+ color='Origin:N',+ tooltip=['Origin:N', alt.Tooltip('density:Q', format='.3f')]+ ).properties(+ width=400,+ height=300,+ title='MPG Distribution by Origin'+ ).interactive()++ return chart++ create_distribution_plot()+ return (create_distribution_plot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/altair-14.py b/marimo/_snippets/data/altair-14.pynew file mode 100644index 0000000000..908d6d086b--- /dev/null+++ b/marimo/_snippets/data/altair-14.py@@ -0,0 +1,76 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Visualization: Multi-View Dashboard in Altair++ Create interactive dashboards using `alt.vconcat()` and `alt.hconcat()`.+ Demonstrates linked views with `alt.selection()` for cross-filtering data.+ """+ )+ return+++def _():+ from vega_datasets import data+ import altair as alt+ return alt, data+++def _(alt, data):+ def create_dashboard():+ # Load dataset+ source = data.cars()++ # Create selection that links all views+ brush = alt.selection_interval(name='select')++ # Scatter plot+ scatter = alt.Chart(source).mark_point().encode(+ x='Horsepower:Q',+ y='Miles_per_Gallon:Q',+ color=alt.condition(brush, 'Origin:N', alt.value('lightgray'))+ ).properties(+ width=300,+ height=200+ ).add_params(brush)++ # Histogram+ hist = alt.Chart(source).mark_bar().encode(+ x='Miles_per_Gallon:Q',+ y='count()',+ color='Origin:N'+ ).transform_filter(+ brush+ ).properties(+ width=300,+ height=100+ )++ # Combine views+ chart = alt.hconcat(scatter, hist)++ return chart++ create_dashboard()+ return (create_dashboard,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/altair-9.py b/marimo/_snippets/data/altair-9.pynew file mode 100644index 0000000000..ebfc7aa3df--- /dev/null+++ b/marimo/_snippets/data/altair-9.py@@ -0,0 +1,65 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Visualization: Heat Map in Altair++ This snippet demonstrates creating a heat map visualization using Altair's+ `rect` mark type with color encoding. Heat maps are excellent for showing+ patterns in matrix-structured data.+ """+ )+ return+++def _():+ from vega_datasets import data+ import altair as alt+ import pandas as pd+ return alt, data, pd+++def _(alt, data):+ def create_heatmap():++ # Load and prepare data+ source = data.seattle_weather()+ # Create heatmap+ chart = alt.Chart(source).mark_rect().encode(+ x=alt.X('date:O', timeUnit='month', title='Month'),+ y=alt.Y('date:O', timeUnit='day', title='Day'),+ color=alt.Color('temp_max:Q', title='Maximum Temperature (°C)'),+ tooltip=[+ alt.Tooltip('monthdate(date):T', title='Date'),+ alt.Tooltip('temp_max:Q', title='Max Temperature')+ ]+ ).properties(+ width=300,+ height=200,+ title='Seattle Weather Heat Map'+ ).interactive()++ return chart++ create_heatmap()+ return (create_heatmap,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-0.py b/marimo/_snippets/data/duckdb-0.pynew file mode 100644index 0000000000..9e86f17310--- /dev/null+++ b/marimo/_snippets/data/duckdb-0.py@@ -0,0 +1,68 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: Basic SQL Querying and DataFrame Integration++ This snippet demonstrates how to use `marimo`'s SQL cells to execute+ queries against a local Pandas DataFrame. We leverage parameterized+ queries through f-string interpolation.+ """+ )+ return+++def _():+ import polars as pl+ # Create a sample DataFrame+ data = {+ 'id': list(range(1, 11)),+ 'value': [x * 10 for x in range(1, 11)]+ }+ df = pl.DataFrame(data)+ return data, df, pl+++def _():+ max_rows = 5+ return (max_rows,)+++def _(df, max_rows, mo):+ limited_df = mo.sql(+ f"""+ SELECT * FROM df LIMIT {max_rows}+ """+ )+ return (limited_df,)+++def _(df, max_rows, mo):+ result_df = mo.sql(+ f"""+ SELECT * FROM df WHERE value > {max_rows * 10}+ """+ )+ return (result_df,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-1.py b/marimo/_snippets/data/duckdb-1.pynew file mode 100644index 0000000000..e4996faa81--- /dev/null+++ b/marimo/_snippets/data/duckdb-1.py@@ -0,0 +1,45 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: CSV File Ingestion++ This snippet demonstrates how to query CSV files directly using DuckDB.+ """+ )+ return+++def _():+ csv_path = 'sample-file.csv'+ return (csv_path,)+++def _(csv_path, mo):+ query = mo.sql(+ f"""+ SELECT * FROM read_csv('{csv_path}', AUTO_DETECT=TRUE)+ LIMIT 10+ """+ )+ return (query,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-2.py b/marimo/_snippets/data/duckdb-2.pynew file mode 100644index 0000000000..80d0590ef6--- /dev/null+++ b/marimo/_snippets/data/duckdb-2.py@@ -0,0 +1,45 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: Persistent Database Connection++ This snippet demonstrates connecting to a persistent DuckDB database+ by specifying a database file, performing DDL/DML operations, and querying data.+ """+ )+ return+++def _():+ # Define the persistent database file name+ db_file = "persistent_db.duckdb"+ return (db_file,)+++def _(mo, persistent_table):+ # Using mo.sql, we create a table (if it doesn't already exist) and insert sample data.+ mo.sql("CREATE TABLE IF NOT EXISTS persistent_table (id INTEGER, value DOUBLE)")+ mo.sql("INSERT INTO persistent_table VALUES (1, 10.5), (2, 20.5)")+ result_df = mo.sql("SELECT * FROM persistent_table")+ return persistent_table, result_df+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-3.py b/marimo/_snippets/data/duckdb-3.pynew file mode 100644index 0000000000..d7f163a663--- /dev/null+++ b/marimo/_snippets/data/duckdb-3.py@@ -0,0 +1,68 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: Advanced SQL with Aggregations & Window Functions++ This snippet demonstrates advanced SQL queries including group-by aggregations+ and window functions (e.g., cumulative sums) using DuckDB.+ """+ )+ return+++def _():+ import polars as pl+ # Create sample DataFrame+ data = {+ 'group': ['A', 'A', 'B', 'B', 'C', 'C'],+ 'value': [10, 15, 20, 25, 30, 35]+ }+ df = pl.DataFrame(data)+ return data, df, pl+++def _(df, mo):+ agg_df = mo.sql(+ f"""+ SELECT+ "group",+ CAST(AVG(value) AS FLOAT) as avg_value+ FROM df+ GROUP BY "group"+ """+ )+ return (agg_df,)+++def _(df, mo):+ window_df = mo.sql(+ f"""+ SELECT+ *,+ CAST(SUM(value) OVER (PARTITION BY "group" ORDER BY value) AS FLOAT) as cumulative_sum+ FROM df+ """+ )+ return (window_df,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-4.py b/marimo/_snippets/data/duckdb-4.pynew file mode 100644index 0000000000..2b595a156f--- /dev/null+++ b/marimo/_snippets/data/duckdb-4.py@@ -0,0 +1,60 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: Parameterized & Reactive SQL Queries++ This snippet shows how to parameterize SQL queries with Python variables+ in marimo, allowing queries to dynamically reflect changes in Python values.+ """+ )+ return+++def _():+ import polars as pl+ # Create a sample DataFrame for reactive filtering+ data = {'id': list(range(1, 21)), 'score': [x * 5 for x in range(1, 21)]}+ df = pl.DataFrame(data)+ return data, df, pl+++def _(mo):+ min_score = mo.ui.number(label="Minimum Score", value=50, start=0)+ return (min_score,)+++def _(min_score):+ min_score+ return+++def _(df, min_score, mo):+ result = mo.sql(+ f"""+ SELECT * FROM df WHERE score >= {min_score.value}+ """+ )+ return (result,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-5.py b/marimo/_snippets/data/duckdb-5.pynew file mode 100644index 0000000000..6a450eadee--- /dev/null+++ b/marimo/_snippets/data/duckdb-5.py@@ -0,0 +1,56 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: Join Operations & Multi-Table Queries++ This snippet demonstrates how to perform JOIN operations between+ two DataFrames using DuckDB's SQL engine within marimo.+ """+ )+ return+++def _():+ import polars as pl+ # Create two sample DataFrames to join+ df1 = pl.DataFrame({+ 'id': [1, 2, 3, 4],+ 'value1': ['A', 'B', 'C', 'D']+ })+ df2 = pl.DataFrame({+ 'id': [3, 4, 5, 6],+ 'value2': ['X', 'Y', 'Z', 'W']+ })+ return df1, df2, pl+++def _(df1, df2, mo):+ join_df = mo.sql(+ f"""+ SELECT a.id, a.value1, b.value2+ FROM df1 a+ INNER JOIN df2 b ON a.id = b.id+ """+ )+ return (join_df,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-6.py b/marimo/_snippets/data/duckdb-6.pynew file mode 100644index 0000000000..b2fb3471ee--- /dev/null+++ b/marimo/_snippets/data/duckdb-6.py@@ -0,0 +1,55 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: Transaction & Error Handling in DML Operations++ This snippet demonstrates transaction management in DuckDB+ using SQLAlchemy. A transaction is used for multiple DML operations,+ and errors are caught and reported. The final result is printed in a+ separate cell.+ """+ )+ return+++def _():+ from sqlalchemy import create_engine+ # Create an in-memory DuckDB engine using SQLAlchemy+ engine = create_engine("duckdb:///:memory:")+ return create_engine, engine+++def _(engine, mo):+ try:+ # Begin a transaction and execute DML operations+ with engine.begin() as conn:+ conn.execute("CREATE OR REPLACE TABLE transaction_table (id INTEGER, name VARCHAR)")+ conn.execute("INSERT INTO transaction_table VALUES (1, 'Alice'), (2, 'Bob')")+ conn.execute("UPDATE transaction_table SET name = 'Charlie' WHERE id = 2")+ result = conn.execute("SELECT * FROM transaction_table").fetchall()+ print("Transaction successful; changes committed.")+ except Exception as e:+ mo.md(f"Transaction error: {e}")+ result = []+ return conn, result+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-7.py b/marimo/_snippets/data/duckdb-7.pynew file mode 100644index 0000000000..b76f29f96a--- /dev/null+++ b/marimo/_snippets/data/duckdb-7.py@@ -0,0 +1,45 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: JSON File Ingestion++ This snippet demonstrates how to query JSON files directly using DuckDB.+ """+ )+ return+++def _():+ json_path = 'sample-file.json'+ return (json_path,)+++def _(json_path, mo):+ query = mo.sql(+ f"""+ SELECT * FROM read_json_auto('{json_path}')+ LIMIT 10+ """+ )+ return (query,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/duckdb-8.py b/marimo/_snippets/data/duckdb-8.pynew file mode 100644index 0000000000..8907a60887--- /dev/null+++ b/marimo/_snippets/data/duckdb-8.py@@ -0,0 +1,45 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # DuckDB: Parquet File Ingestion++ This snippet demonstrates how to query Parquet files directly using DuckDB.+ """+ )+ return+++def _():+ parquet_path = 'sample-file.parquet'+ return (parquet_path,)+++def _(mo, parquet_path):+ query = mo.sql(+ f"""+ SELECT * FROM read_parquet('{parquet_path}')+ LIMIT 10+ """+ )+ return (query,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-0.py b/marimo/_snippets/data/matplotlib-0.pynew file mode 100644index 0000000000..6488f594d6--- /dev/null+++ b/marimo/_snippets/data/matplotlib-0.py@@ -0,0 +1,64 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Basic Line and Scatter Plots++ Create basic plots using `plt.plot()` and `plt.scatter()`. Shows line styles,+ markers, and colors with `plt.legend()` for multiple series.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_line_scatter_plot():+ # Generate sample data+ x = np.linspace(0, 10, 100)+ y1 = np.sin(x)+ y2 = np.cos(x)++ # Create figure and axis+ fig, ax = plt.subplots(figsize=(10, 6))++ # Plot multiple lines with different styles+ ax.plot(x, y1, 'b-', label='sin(x)', linewidth=2)+ ax.scatter(x[::10], y2[::10], c='r', label='cos(x)', s=50)++ # Customize the plot+ ax.set_xlabel('x')+ ax.set_ylabel('y')+ ax.set_title('Basic Line and Scatter Plot')+ ax.grid(True, linestyle='--', alpha=0.7)+ ax.legend()++ return ax++ create_line_scatter_plot()+ return (create_line_scatter_plot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-1.py b/marimo/_snippets/data/matplotlib-1.pynew file mode 100644index 0000000000..92f6838760--- /dev/null+++ b/marimo/_snippets/data/matplotlib-1.py@@ -0,0 +1,70 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Multiple Subplots Layout++ Create multiple subplots using `plt.subplots()`. Common for comparing different+ views of data with `sharex` and `sharey` options.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_multi_subplot():+ # Generate sample data+ x = np.linspace(0, 10, 100)+ y1 = np.sin(x)+ y2 = np.exp(-x/3)++ # Create figure with 2x2 subplots+ fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 8))++ # Plot different visualizations+ ax1.plot(x, y1, 'b-', label='Sine')+ ax1.set_title('Line Plot')+ ax1.legend()++ ax2.scatter(x[::5], y2[::5], c='r', s=50, alpha=0.5)+ ax2.set_title('Scatter Plot')++ ax3.fill_between(x, y1, alpha=0.3)+ ax3.set_title('Area Plot')++ ax4.hist(y2, bins=20, alpha=0.7)+ ax4.set_title('Histogram')++ # Adjust layout+ plt.tight_layout()++ return ax1, ax2, ax3, ax4++ create_multi_subplot()+ return (create_multi_subplot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-10.py b/marimo/_snippets/data/matplotlib-10.pynew file mode 100644index 0000000000..cab6c17248--- /dev/null+++ b/marimo/_snippets/data/matplotlib-10.py@@ -0,0 +1,67 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Dual Y-Axis Visualization++ Create plots with two different y-scales using `twinx()`.+ Common for comparing different metrics on same x-axis.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_twin_axes():+ # Generate sample data+ x = np.linspace(0, 10, 100)+ y1 = np.sin(x) * 10 # Large scale+ y2 = np.cos(x) * 0.1 # Small scale++ # Create figure and axis+ fig, ax1 = plt.subplots(figsize=(8, 5))++ # Plot on primary y-axis+ color = 'tab:blue'+ ax1.set_xlabel('Time')+ ax1.set_ylabel('Large Scale', color=color)+ ax1.plot(x, y1, color=color)+ ax1.tick_params(axis='y', labelcolor=color)++ # Create twin axis+ ax2 = ax1.twinx()+ color = 'tab:red'+ ax2.set_ylabel('Small Scale', color=color)+ ax2.plot(x, y2, color=color)+ ax2.tick_params(axis='y', labelcolor=color)++ return ax1, ax2++ create_twin_axes()+ return (create_twin_axes,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-11.py b/marimo/_snippets/data/matplotlib-11.pynew file mode 100644index 0000000000..368a29063d--- /dev/null+++ b/marimo/_snippets/data/matplotlib-11.py@@ -0,0 +1,68 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Legend Customization and Styling++ Customize legend placement, styling, and handles.+ Shows common legend patterns in data visualization.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_advanced_legend():+ # Generate data+ x = np.linspace(0, 10, 100)+ y1 = np.sin(x)+ y2 = np.cos(x)++ # Create plot with custom legend+ fig, ax = plt.subplots(figsize=(8, 5))++ # Multiple plot types+ line1 = ax.plot(x, y1, 'b-', label='Sine')[0]+ scatter = ax.scatter(x[::10], y2[::10], c='r', label='Cosine')++ # Custom legend+ ax.legend(+ [line1, scatter],+ ['Sin(x)', 'Cos(x)'],+ loc='upper right',+ bbox_to_anchor=(1.15, 1),+ frameon=True,+ fancybox=True,+ shadow=True+ )++ return ax++ create_advanced_legend()+ return (create_advanced_legend,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-2.py b/marimo/_snippets/data/matplotlib-2.pynew file mode 100644index 0000000000..4d2a7984de--- /dev/null+++ b/marimo/_snippets/data/matplotlib-2.py@@ -0,0 +1,72 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Distribution Plots with Histograms and Box Plots++ Create statistical plots using `hist()`, `boxplot()`, and `violinplot()`.+ Common for data distribution analysis with customizable bins and orientations.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_statistical_plots():+ # Generate sample data+ np.random.seed(42)+ data1 = np.random.normal(100, 10, 200)+ data2 = np.random.normal(90, 20, 200)+ data = [data1, data2]++ # Create figure with three subplots+ fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))++ # Histogram+ ax1.hist(data1, bins=30, alpha=0.7, color='skyblue', label='Distribution 1')+ ax1.hist(data2, bins=30, alpha=0.7, color='lightgreen', label='Distribution 2')+ ax1.set_title('Histogram')+ ax1.legend()++ # Box Plot+ ax2.boxplot(data, tick_labels=['Dist 1', 'Dist 2'])+ ax2.set_title('Box Plot')++ # Violin Plot+ ax3.violinplot(data)+ ax3.set_title('Violin Plot')+ ax3.set_xticks([1, 2])+ ax3.set_xticklabels(['Dist 1', 'Dist 2'])++ plt.tight_layout()++ return ax1, ax2, ax3++ create_statistical_plots()+ return (create_statistical_plots,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-3.py b/marimo/_snippets/data/matplotlib-3.pynew file mode 100644index 0000000000..4f6249b43a--- /dev/null+++ b/marimo/_snippets/data/matplotlib-3.py@@ -0,0 +1,79 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Time Series with Custom Formatting++ Create time series visualizations with `plot_date()` and custom date formatting.+ Shows rolling averages and confidence intervals using `fill_between()`.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ import pandas as pd+ return np, pd, plt+++def _(np, pd, plt):+ def create_time_series_plot():+ # Generate sample time series data+ dates = pd.date_range(start='2023-01-01', periods=100, freq='D')+ np.random.seed(42)+ values = np.random.randn(100).cumsum()++ # Calculate rolling statistics+ window = 20+ rolling_mean = pd.Series(values).rolling(window=window).mean()+ rolling_std = pd.Series(values).rolling(window=window).std()++ # Create the plot+ fig, ax = plt.subplots(figsize=(12, 6))++ # Plot raw data and rolling mean+ ax.plot(dates, values, 'k-', alpha=0.3, label='Raw Data')+ ax.plot(dates, rolling_mean, 'b-', label=f'{window}-Day Mean')++ # Add confidence interval+ ax.fill_between(dates,+ rolling_mean - 2*rolling_std,+ rolling_mean + 2*rolling_std,+ color='b', alpha=0.1, label='95% Confidence')++ # Customize the plot+ ax.set_title('Time Series with Rolling Statistics')+ ax.set_xlabel('Date')+ ax.set_ylabel('Value')+ ax.grid(True, linestyle='--', alpha=0.7)+ ax.legend()++ # Format date axis+ plt.gcf().autofmt_xdate()++ return ax++ create_time_series_plot()+ return (create_time_series_plot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-4.py b/marimo/_snippets/data/matplotlib-4.pynew file mode 100644index 0000000000..7afcf196e2--- /dev/null+++ b/marimo/_snippets/data/matplotlib-4.py@@ -0,0 +1,63 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Styling and Themes++ Apply custom styles using `plt.style.use()` and customize plots with+ `rcParams`. Common for creating publication-quality figures.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_styled_plot():+ # Set style and custom parameters+ plt.style.use('ggplot') # Using built-in ggplot style+ plt.rcParams['figure.figsize'] = [8, 5]+ plt.rcParams['axes.grid'] = True++ # Generate sample data+ x = np.linspace(0, 10, 50)+ y = np.sin(x) + np.random.normal(0, 0.2, 50)++ # Create styled plot+ fig, ax = plt.subplots()+ ax.scatter(x, y, c='crimson', alpha=0.6)+ ax.set_title('Styled Scatter Plot', fontsize=12, pad=10)++ # Add minimal styling+ ax.spines['top'].set_visible(False)+ ax.spines['right'].set_visible(False)++ return ax++ create_styled_plot()+ return (create_styled_plot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-5.py b/marimo/_snippets/data/matplotlib-5.pynew file mode 100644index 0000000000..39f7a718d0--- /dev/null+++ b/marimo/_snippets/data/matplotlib-5.py@@ -0,0 +1,63 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Data Point Labels and Explanatory Notes++ Add annotations using `annotate()` and text using `text()`.+ Common for highlighting specific data points and adding explanations.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_annotated_plot():+ # Create data+ x = np.linspace(0, 10, 20)+ y = np.sin(x)++ # Create plot with annotations+ fig, ax = plt.subplots(figsize=(8, 5))+ ax.plot(x, y, 'b-')++ # Add arrow annotation+ ax.annotate('Maximum',+ xy=(4.7, 1.0), # Point to annotate+ xytext=(5.5, 0.5), # Text position+ arrowprops=dict(facecolor='black', shrink=0.05))++ # Add text box+ ax.text(2, -0.5, 'Sine Wave',+ bbox=dict(facecolor='white', alpha=0.7))++ return ax++ create_annotated_plot()+ return (create_annotated_plot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-6.py b/marimo/_snippets/data/matplotlib-6.pynew file mode 100644index 0000000000..b67ba86dd6--- /dev/null+++ b/marimo/_snippets/data/matplotlib-6.py@@ -0,0 +1,62 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Heatmaps with Colormaps++ Create heatmaps using `imshow()` with custom colormaps.+ Common for visualizing matrices, correlations, and grid data.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_heatmap():+ # Create sample correlation matrix+ np.random.seed(42)+ data = np.random.randn(5, 5)+ corr = np.corrcoef(data)++ # Create heatmap+ fig, ax = plt.subplots(figsize=(7, 6))+ im = ax.imshow(corr, cmap='coolwarm', vmin=-1, vmax=1)++ # Add colorbar+ plt.colorbar(im)++ # Add labels+ ax.set_xticks(range(5))+ ax.set_yticks(range(5))+ ax.set_title('Correlation Matrix')++ return ax++ create_heatmap()+ return (create_heatmap,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-7.py b/marimo/_snippets/data/matplotlib-7.pynew file mode 100644index 0000000000..3e8d846745--- /dev/null+++ b/marimo/_snippets/data/matplotlib-7.py@@ -0,0 +1,60 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: 3D Surface Plots++ Create 3D surface plots using `ax.plot_surface()`.+ Common for visualizing mathematical functions and terrain data.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ from mpl_toolkits.mplot3d import Axes3D+ return Axes3D, np, plt+++def _(np, plt):+ def create_3d_surface():+ # Create data for 3D plot+ x = np.linspace(-2, 2, 30)+ y = np.linspace(-2, 2, 30)+ X, Y = np.meshgrid(x, y)+ Z = np.sin(np.sqrt(X**2 + Y**2))++ # Create 3D plot+ fig = plt.figure(figsize=(8, 6))+ ax = fig.add_subplot(111, projection='3d')+ surf = ax.plot_surface(X, Y, Z, cmap='viridis')++ # Add colorbar+ fig.colorbar(surf)++ return ax++ create_3d_surface()+ return (create_3d_surface,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-8.py b/marimo/_snippets/data/matplotlib-8.pynew file mode 100644index 0000000000..be788922e3--- /dev/null+++ b/marimo/_snippets/data/matplotlib-8.py@@ -0,0 +1,59 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Error Bars++ Add error bars using `errorbar()`. Common in scientific visualization+ to show measurement uncertainty or variation in data.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import numpy as np+ return np, plt+++def _(np, plt):+ def create_error_bar_plot():+ # Create sample data with errors+ x = np.linspace(0, 10, 5)+ y = np.exp(-x/2)+ y_err = 0.1 + 0.1*np.random.rand(len(x))++ # Create error bar plot+ fig, ax = plt.subplots(figsize=(8, 5))+ ax.errorbar(x, y, yerr=y_err, fmt='o-', capsize=5,+ ecolor='gray', markersize=8)++ ax.set_xlabel('X')+ ax.set_ylabel('Y')+ ax.grid(True, linestyle='--', alpha=0.7)++ return ax++ create_error_bar_plot()+ return (create_error_bar_plot,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/matplotlib-9.py b/marimo/_snippets/data/matplotlib-9.pynew file mode 100644index 0000000000..f46df0f6c8--- /dev/null+++ b/marimo/_snippets/data/matplotlib-9.py@@ -0,0 +1,63 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Matplotlib: Advanced Subplot Layouts++ Different subplot arrangements using `GridSpec` and `subplot2grid`.+ Shows uneven layouts and spanning multiple grid cells.+ """+ )+ return+++def _():+ import matplotlib.pyplot as plt+ import matplotlib.gridspec as gridspec+ import numpy as np+ return gridspec, np, plt+++def _(gridspec, np, plt):+ def create_advanced_subplots():+ # Create figure with GridSpec+ fig = plt.figure(figsize=(12, 8))+ gs = gridspec.GridSpec(3, 3)++ # Spanning multiple cells+ ax1 = fig.add_subplot(gs[0, :]) # Span all columns+ ax2 = fig.add_subplot(gs[1:, 0:2]) # Span 2 rows, 2 columns+ ax3 = fig.add_subplot(gs[1:, 2]) # Span 2 rows, 1 column++ # Add sample plots+ x = np.linspace(0, 10, 100)+ ax1.plot(x, np.sin(x))+ ax2.scatter(x[::5], np.cos(x[::5]))+ ax3.hist(np.random.randn(100))++ plt.tight_layout()++ return ax1, ax2, ax3++ create_advanced_subplots()+ return (create_advanced_subplots,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-26.py b/marimo/_snippets/data/pandas-26.pynew file mode 100644index 0000000000..14400d9066--- /dev/null+++ b/marimo/_snippets/data/pandas-26.py@@ -0,0 +1,42 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Memory Optimization with Category Type""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame+ df = pd.DataFrame({+ 'id': range(1000),+ 'status': ['active', 'inactive', 'pending'] * 333 + ['active'],+ 'category': ['A', 'B', 'C', 'D'] * 250+ })++ # Convert string columns to category+ # Refer: https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html+ df['status'] = df['status'].astype('category')+ df['category'] = df['category'].astype('category')++ df.dtypes+ return df, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-27.py b/marimo/_snippets/data/pandas-27.pynew file mode 100644index 0000000000..09295bb281--- /dev/null+++ b/marimo/_snippets/data/pandas-27.py@@ -0,0 +1,47 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Multiple Column Aggregations""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame+ df = pd.DataFrame({+ 'group': ['A', 'A', 'B', 'B', 'B'],+ 'numeric1': [10, 20, 30, 40, 50],+ 'numeric2': [100, 200, 300, 400, 500],+ 'text': ['x', 'y', 'z', 'x', 'y']+ })++ # Multiple aggregations+ agg_stats = df.groupby('group').agg(+ sum_numeric1=('numeric1', 'sum'),+ mean_numeric1=('numeric1', 'mean'),+ min_numeric2=('numeric2', 'min'),+ max_numeric2=('numeric2', 'max'),+ unique_texts=('text', 'nunique')+ ).reset_index()++ agg_stats+ return agg_stats, df, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-28.py b/marimo/_snippets/data/pandas-28.pynew file mode 100644index 0000000000..210ba49030--- /dev/null+++ b/marimo/_snippets/data/pandas-28.py@@ -0,0 +1,50 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Pivot Table Operations""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame+ df = pd.DataFrame({+ 'date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02'],+ 'category': ['A', 'B', 'A', 'B'],+ 'value1': [100, 200, 150, 250],+ 'value2': [10, 20, 15, 25]+ })++ # Create pivot table+ pivot_df = pd.pivot_table(+ df,+ index='date',+ columns='category',+ values=['value1', 'value2']+ ).reset_index()++ # Flatten column names for better display+ pivot_df.columns = [f"{col[0]}_{col[1]}" if isinstance(col, tuple) else col+ for col in pivot_df.columns]++ pivot_df+ return df, pd, pivot_df+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-29.py b/marimo/_snippets/data/pandas-29.pynew file mode 100644index 0000000000..43db1501d0--- /dev/null+++ b/marimo/_snippets/data/pandas-29.py@@ -0,0 +1,44 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Rolling and Expanding Window Statistics""")+ return+++def _():+ import pandas as pd++ # Create sample time series DataFrame+ df = pd.DataFrame({+ 'date': pd.date_range('2024-01-01', periods=5),+ 'value': [10, 20, 15, 30, 25]+ }).set_index('date')++ # Calculate multiple window statistics+ window_stats = pd.DataFrame({+ 'original': df['value'],+ 'rolling_mean': df['value'].rolling(window=3).mean(),+ 'rolling_std': df['value'].rolling(window=3).std(),+ 'expanding_max': df['value'].expanding().max()+ })++ window_stats+ return df, pd, window_stats+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-30.py b/marimo/_snippets/data/pandas-30.pynew file mode 100644index 0000000000..6a5119b5a8--- /dev/null+++ b/marimo/_snippets/data/pandas-30.py@@ -0,0 +1,43 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Missing Data Handling""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame with missing values+ df = pd.DataFrame({+ 'A': [1, None, 3, None, 5],+ 'B': [None, 2, 3, 4, 5],+ 'C': ['a', 'b', None, 'd', 'e']+ })++ # Common missing data operations+ cleaned_df = df.copy()+ cleaned_df['A'] = df['A'].fillna(df['A'].mean()) # Fill numeric with mean+ cleaned_df['B'] = df['B'].fillna(0) # Fill numeric with zero+ cleaned_df['C'] = df['C'].fillna('missing') # Fill strings with value++ cleaned_df+ return cleaned_df, df, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-31.py b/marimo/_snippets/data/pandas-31.pynew file mode 100644index 0000000000..24e6ee008d--- /dev/null+++ b/marimo/_snippets/data/pandas-31.py@@ -0,0 +1,46 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Advanced DateTime Operations""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame with datetime data+ df = pd.DataFrame({+ 'date': pd.date_range('2024-01-01', periods=5),+ 'value': [100, 200, 150, 300, 250]+ })++ # DateTime operations+ date_features = pd.DataFrame({+ 'original_date': df['date'],+ 'year': df['date'].dt.year,+ 'month': df['date'].dt.month,+ 'day': df['date'].dt.day,+ 'day_name': df['date'].dt.day_name(),+ 'is_month_end': df['date'].dt.is_month_end+ })++ date_features+ return date_features, df, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-32.py b/marimo/_snippets/data/pandas-32.pynew file mode 100644index 0000000000..71c8e7ffa3--- /dev/null+++ b/marimo/_snippets/data/pandas-32.py@@ -0,0 +1,42 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Boolean Indexing and Filtering""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame+ df = pd.DataFrame({+ 'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],+ 'age': [25, 30, 35, 28, 22],+ 'salary': [50000, 60000, 75000, 62000, 45000],+ 'department': ['IT', 'HR', 'IT', 'Finance', 'HR']+ })++ # Multiple boolean conditions+ mask = (df['age'] > 25) & (df['salary'] > 60000)+ filtered_df = df[mask]++ filtered_df+ return df, filtered_df, mask, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-33.py b/marimo/_snippets/data/pandas-33.pynew file mode 100644index 0000000000..417f512c02--- /dev/null+++ b/marimo/_snippets/data/pandas-33.py@@ -0,0 +1,47 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Merge Operations""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrames+ df1 = pd.DataFrame({+ 'id': [1, 2, 3, 4],+ 'name': ['Alice', 'Bob', 'Charlie', 'David'],+ 'dept': ['IT', 'HR', 'IT', 'Finance']+ })++ df2 = pd.DataFrame({+ 'id': [1, 2, 3, 5],+ 'salary': [50000, 60000, 75000, 65000],+ 'bonus': [5000, 6000, 7500, 6500]+ })++ # Different types of joins+ merged_inner = pd.merge(df1, df2, on='id', how='inner')+ merged_left = pd.merge(df1, df2, on='id', how='left')++ merged_inner+ return df1, df2, merged_inner, merged_left, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-34.py b/marimo/_snippets/data/pandas-34.pynew file mode 100644index 0000000000..8fe56cad63--- /dev/null+++ b/marimo/_snippets/data/pandas-34.py@@ -0,0 +1,56 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Memory Optimization and Type Management""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame with different data types+ df = pd.DataFrame({+ 'int_col': range(1000),+ 'float_col': [1.5] * 1000,+ 'str_col': ['A'] * 1000,+ 'category_col': ['A', 'B', 'C'] * 333 + ['A'] # Make it 1000 rows+ })++ # Memory optimization+ df['category_col'] = df['category_col'].astype('category')+ df['int_col'] = df['int_col'].astype('int32')++ # Get memory usage+ memory_usage = df.memory_usage(deep=True)+ dtypes = df.dtypes+ return df, dtypes, memory_usage, pd+++def _(memory_usage):+ memory_usage+ return+++def _(dtypes):+ dtypes+ return+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-35.py b/marimo/_snippets/data/pandas-35.pynew file mode 100644index 0000000000..7f33b3670b--- /dev/null+++ b/marimo/_snippets/data/pandas-35.py@@ -0,0 +1,46 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Reshaping Data with Melt""")+ return+++def _():+ import pandas as pd++ # Create wide format data+ df = pd.DataFrame({+ 'id': ['A', 'B', 'C'],+ 'score_2020': [75, 85, 95],+ 'score_2021': [80, 90, 100],+ 'score_2022': [85, 95, 105]+ })++ # Reshape from wide to long format+ melted_df = df.melt(+ id_vars=['id'],+ value_vars=['score_2020', 'score_2021', 'score_2022'],+ var_name='year',+ value_name='score'+ )++ melted_df+ return df, melted_df, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/pandas-36.py b/marimo/_snippets/data/pandas-36.pynew file mode 100644index 0000000000..7e7097260f--- /dev/null+++ b/marimo/_snippets/data/pandas-36.py@@ -0,0 +1,47 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(r"""# Pandas: Advanced Groupby Operations""")+ return+++def _():+ import pandas as pd++ # Create sample DataFrame+ df = pd.DataFrame({+ 'group': ['A', 'A', 'B', 'B', 'C'],+ 'value1': [10, 20, 30, 40, 50],+ 'value2': [1, 2, 3, 4, 5]+ })++ # Multiple groupby operations+ grouped_stats = df.groupby('group').agg({+ 'value1': ['sum', 'mean', 'count'],+ 'value2': ['min', 'max']+ }).round(2)++ # Flatten column names+ grouped_stats.columns = [f"{col[0]}_{col[1]}" for col in grouped_stats.columns]+ grouped_stats = grouped_stats.reset_index()++ grouped_stats+ return df, grouped_stats, pd+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-0.py b/marimo/_snippets/data/polars-0.pynew file mode 100644index 0000000000..ea464b7aae--- /dev/null+++ b/marimo/_snippets/data/polars-0.py@@ -0,0 +1,63 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Lazy Evaluation++ This snippet shows how to use Polars' `lazy()` evaluation for optimized query planning,+ expression-based operations, and memory-efficient data processing. See example below.+ """+ )+ return+++def _():+ import polars as pl+ import numpy as np++ # Create sample DataFrame with numeric data+ df = pl.DataFrame({+ 'id': range(1000),+ 'category': ['A', 'B', 'C', 'D'] * 250,+ 'values': np.arange(0, 2000, 2)+ })++ # Demonstrate lazy evaluation with optimized query+ lazy_query = (+ df.lazy()+ .filter(pl.col('values') > 500)+ .group_by('category')+ .agg([+ pl.col('values').mean().alias('avg_value'),+ pl.col('values').count().alias('count')+ ])+ .sort('avg_value', descending=True)+ )++ # Show optimization plan+ print("Lazy Query Plan:")+ print(lazy_query.explain())++ # Execute lazy query+ result = lazy_query.collect()+ result+ return df, lazy_query, np, pl, result+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-1.py b/marimo/_snippets/data/polars-1.pynew file mode 100644index 0000000000..cf14715388--- /dev/null+++ b/marimo/_snippets/data/polars-1.py@@ -0,0 +1,58 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def __(mo):+ mo.md(+ r"""+ # Polars: Rolling Averages and Z-Score Calculations++ This snippet shows advanced column operations in Polars using `rolling_mean()`, `over()` aggregations,+ and type casting with the expression API.+ """+ )+ return+++def __():+ import polars as pl+ from datetime import datetime, timedelta++ # Create sample DataFrame with proper datetime+ df = pl.DataFrame({+ 'id': range(1000),+ 'value': [1.5, 2.5, 3.5] * 333 + [1.5],+ 'category': ['A', 'B', 'C'] * 333 + ['A'],+ 'date': [(datetime(2024, 1, 1) + timedelta(days=x)) for x in range(1000)]+ })++ # Demonstrate advanced expressions+ result = (+ df.lazy()+ .with_columns([+ pl.col('value').sum().over('category').alias('category_sum'),+ pl.col('value').rolling_mean(3).alias('rolling_avg'),+ pl.col('date').dt.month().cast(pl.Categorical).alias('month'),+ ((pl.col('value') - pl.col('value').mean()) /+ pl.col('value').std()).alias('zscore')+ ])+ .collect()+ )++ return df, result, pl+++def __():+ import marimo as mo+ return mo,+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-10.py b/marimo/_snippets/data/polars-10.pynew file mode 100644index 0000000000..29120caffc--- /dev/null+++ b/marimo/_snippets/data/polars-10.py@@ -0,0 +1,70 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Data Standardization and Group Comparisons++ This snippet demonstrates statistical operations in Polars including summary statistics,+ correlations, standardization, and group comparisons.++ Example: `df.select([pl.all()]).describe()` for summary statistics+ """+ )+ return+++def _():+ import polars as pl+ import numpy as np++ # Create sample dataset+ df = pl.DataFrame({+ 'A': np.random.normal(10, 2, 1000),+ 'B': np.random.normal(20, 5, 1000),+ 'C': np.random.normal(0, 1, 1000),+ 'group': ['X', 'Y'] * 500+ })++ # Basic statistics+ summary = df.select([+ pl.all().exclude('group'),+ ]).describe()++ # Correlation matrix+ corr = df.select([+ pl.all().exclude('group')+ ]).corr()++ # Z-score standardization+ z_scores = df.select([+ ((pl.col(c) - pl.col(c).mean()) / pl.col(c).std()).alias(f'{c}_zscore')+ for c in ['A', 'B', 'C']+ ])++ # Group comparison (basic t-test like)+ group_stats = df.group_by('group').agg([+ pl.col('A').mean().alias('mean'),+ pl.col('A').std().alias('std'),+ pl.col('A').count().alias('n')+ ])+ df, summary, corr, z_scores, group_stats+ return corr, df, group_stats, np, pl, summary, z_scores+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-11.py b/marimo/_snippets/data/polars-11.pynew file mode 100644index 0000000000..2324b59d4d--- /dev/null+++ b/marimo/_snippets/data/polars-11.py@@ -0,0 +1,79 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Parquet Operations++ Demonstrates Polars' Parquet capabilities using `scan_parquet()` for+ streaming large Parquet datasets. Shows memory-efficient filtering+ and aggregation with lazy evaluation.++ Example: `pl.scan_parquet("data.parquet").filter(pl.col("value") > 500).collect()`+ """+ )+ return+++def _():+ import polars as pl+ import tempfile+ from pathlib import Path+ import datetime++ # Create sample data+ df = pl.DataFrame({+ 'date': [(datetime.date(2024, 1, 1) + datetime.timedelta(days=x % 366)) for x in range(1000)],+ 'category': ['A', 'B', 'C'] * 333 + ['A'],+ 'value': range(1000)+ })++ # Create temporary directory and save Parquet+ temp_dir = Path(tempfile.mkdtemp())+ parquet_path = temp_dir / 'data.parquet'+ df.write_parquet(+ parquet_path,+ compression='snappy',+ use_pyarrow=True+ )++ # Demonstrate filtered parquet read with aggregation+ parquet_filtered = (+ pl.scan_parquet(parquet_path)+ .filter(pl.col('value') > 500)+ .group_by('category')+ .agg([+ pl.col('value').mean().alias('avg_value'),+ pl.col('value').count().alias('count')+ ])+ .collect()+ )+ parquet_filtered+ return (+ Path,+ datetime,+ df,+ parquet_filtered,+ parquet_path,+ pl,+ temp_dir,+ tempfile,+ )+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-12.py b/marimo/_snippets/data/polars-12.pynew file mode 100644index 0000000000..4b89a141a9--- /dev/null+++ b/marimo/_snippets/data/polars-12.py@@ -0,0 +1,69 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Lazy Evaluation and Parquet Streaming++ Demonstrates Polars' streaming capabilities for large datasets using lazy evaluation.+ Shows how to efficiently process data without loading entire dataset into memory.++ Example: `pl.scan_parquet("data.parquet").filter(pl.col("date").dt.year() == 2024).collect()`+ """+ )+ return+++def _():+ import polars as pl+ import tempfile+ from pathlib import Path+ import datetime++ # Create sample data+ df = pl.DataFrame({+ 'date': [(datetime.date(2024, 1, 1) + datetime.timedelta(days=x % 366)) for x in range(1000)],+ 'category': ['A', 'B', 'C'] * 333 + ['A'],+ 'value': range(1000)+ })++ # Create temporary directory and save files+ temp_dir = Path(tempfile.mkdtemp())+ parquet_path = temp_dir / 'data.parquet'+ df.write_parquet(parquet_path)++ # Demonstrate streaming with lazy evaluation+ streamed = (+ pl.scan_parquet(parquet_path)+ .filter(pl.col('date').dt.year() == 2024)+ .collect()+ )+ streamed+ return (+ Path,+ datetime,+ df,+ parquet_path,+ pl,+ streamed,+ temp_dir,+ tempfile,+ )+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-2.py b/marimo/_snippets/data/polars-2.pynew file mode 100644index 0000000000..ebdc1e1c4f--- /dev/null+++ b/marimo/_snippets/data/polars-2.py@@ -0,0 +1,70 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Memory Optimization with Data Types++ This snippet demonstrates memory optimization in Polars using `Categorical` types for strings,+ smaller numeric types like `Float32`, and lazy evaluation.+ Converting string columns to categorical can reduce memory usage.+ """+ )+ return+++def _():+ import polars as pl+ import numpy as np++ # Create dataset with memory-intensive columns+ df = pl.DataFrame(+ {+ "id": range(100_000),+ # Create longer strings to show memory impact+ "text": [+ f"very_long_string_that_repeats_many_times_{i % 100}"+ for i in range(100_000)+ ],+ "category": np.random.choice(+ ["Category_A", "Category_B", "Category_C"], 100_000+ ),+ "value": np.random.normal(100, 15, 100_000).astype(+ np.float64+ ), # Explicitly use float64+ }+ )++ # Memory before optimization+ print(f"Before: {df.estimated_size() / 1e6:.1f}MB")++ # Optimize memory usage+ df_opt = df.with_columns(+ [+ pl.col("text").cast(pl.Categorical),+ pl.col("category").cast(pl.Categorical),+ pl.col("value").cast(pl.Float32),+ pl.col("id").cast(pl.UInt32), # Optimize integer type+ ]+ )++ print(f"After: {df_opt.estimated_size() / 1e6:.1f}MB")+ return df, df_opt, np, pl+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-3.py b/marimo/_snippets/data/polars-3.pynew file mode 100644index 0000000000..e9908e143f--- /dev/null+++ b/marimo/_snippets/data/polars-3.py@@ -0,0 +1,91 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: High-Performance Joins and Aggregations++ This snippet shows efficient join operations in Polars using `lazy()` evaluation.+ Demonstrates joining DataFrames with different strategies, aggregating results,+ and applying window functions for analysis.+ """+ )+ return+++def _():+ import polars as pl++ # Create sample DataFrames+ df1 = pl.DataFrame({+ 'id': range(1000),+ 'value': [1.5, 2.5, 3.5] * 333 + [1.5],+ 'category': ['A', 'B', 'C'] * 333 + ['A']+ })++ df2 = pl.DataFrame({+ 'id': range(500, 1500), # Overlapping and non-overlapping IDs+ 'other_value': range(1000),+ 'category': ['B', 'C', 'D'] * 333 + ['B']+ })++ # 1. Basic join with aggregations+ basic_join = (+ df1.lazy()+ .join(+ df2.lazy(),+ on='id',+ how='left'+ )+ .group_by('category')+ .agg([+ pl.col('value').mean().alias('avg_value'),+ pl.col('other_value').mean().alias('avg_other_value'),+ pl.col('id').count().alias('count')+ ])+ .sort('category')+ .collect()+ )++ # 2. Advanced join with window functions+ window_ops = (+ df1.lazy()+ .join(+ df2.lazy(),+ on='id',+ how='left'+ )+ .with_columns([+ # Window functions+ pl.col('value').sum().over('category').alias('category_total'),+ pl.col('value').mean().over('category').alias('category_avg'),+ pl.col('value').rank().over('category').alias('rank_in_category'),+ # Rolling calculations+ pl.col('value')+ .rolling_mean(window_size=3)+ .over('category')+ .alias('rolling_avg')+ ])+ .sort(['category', 'id'])+ .collect()+ )+ basic_join, window_ops+ return basic_join, df1, df2, pl, window_ops+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-4.py b/marimo/_snippets/data/polars-4.pynew file mode 100644index 0000000000..3773e9ba82--- /dev/null+++ b/marimo/_snippets/data/polars-4.py@@ -0,0 +1,71 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Dynamic Time Windows and Aggregations++ This snippet shows time series operations in Polars using `dt` expressions for+ parsing and formatting, dynamic time windows with `group_by_dynamic()`,+ and timezone-aware calculations.+ """+ )+ return+++def _():+ import polars as pl+ import numpy as np+ from datetime import datetime, timedelta++ # Create time series data+ dates = [datetime(2024, 1, 1) + timedelta(hours=x) for x in range(1000)]+ df = pl.DataFrame({+ 'timestamp': dates,+ 'value': np.random.normal(0, 1, 1000),+ 'category': ['A', 'B'] * 500+ })++ # Time series operations+ result = (+ df.lazy()+ .with_columns([+ # Convert to timezone-aware datetime+ pl.col('timestamp').dt.replace_time_zone('UTC').alias('timestamp_utc'),+ # Extract components+ pl.col('timestamp').dt.hour().alias('hour'),+ pl.col('timestamp').dt.weekday().alias('weekday') # Fixed: using weekday instead of day_of_week+ ])+ .group_by_dynamic(+ 'timestamp',+ every='1d', # Daily windows+ closed='left'+ )+ .agg([+ pl.col('value').mean().alias('daily_avg'),+ pl.col('value').std().alias('daily_std'),+ pl.col('value').count().alias('count')+ ])+ .sort('timestamp')+ .collect()+ )+ result+ return dates, datetime, df, np, pl, result, timedelta+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-5.py b/marimo/_snippets/data/polars-5.pynew file mode 100644index 0000000000..92c375f180--- /dev/null+++ b/marimo/_snippets/data/polars-5.py@@ -0,0 +1,70 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: CSV Operations++ Demonstrates Polars' CSV capabilities using `scan_csv()` for+ streaming large CSV datasets. Shows memory-efficient filtering+ and aggregation with lazy evaluation.++ Example: `pl.scan_csv("data.csv").filter(pl.col("value") > 500).collect()`+ """+ )+ return+++def _():+ import polars as pl+ import tempfile+ from pathlib import Path+ import datetime++ # Create sample data+ df = pl.DataFrame({+ 'date': [(datetime.date(2024, 1, 1) + datetime.timedelta(days=x % 366)) for x in range(1000)],+ 'category': ['A', 'B', 'C'] * 333 + ['A'],+ 'value': range(1000)+ })++ # Create temporary directory and save CSV+ temp_dir = Path(tempfile.mkdtemp())+ csv_path = temp_dir / 'data.csv'+ df.write_csv(csv_path)++ # Demonstrate filtered CSV read+ csv_filtered = (+ pl.scan_csv(csv_path)+ .filter(pl.col('category') == 'A')+ .collect()+ )+ csv_filtered+ return (+ Path,+ csv_filtered,+ csv_path,+ datetime,+ df,+ pl,+ temp_dir,+ tempfile,+ )+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-6.py b/marimo/_snippets/data/polars-6.pynew file mode 100644index 0000000000..b6c2101047--- /dev/null+++ b/marimo/_snippets/data/polars-6.py@@ -0,0 +1,80 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: String Operations and Pattern Matching++ This snippet demonstrates efficient string operations in Polars using pattern matching,+ transformations, and regular expressions. Shows string cleaning with `str.replace()`,+ pattern extraction with `str.extract()`, and memory optimization using `Categorical` types.++ Example: `df.with_columns(pl.col("text").str.extract(r"pattern_(\d+)", 1))`+ """+ )+ return+++def _():+ import polars as pl++ # Create sample text data with various patterns+ df = pl.DataFrame({+ 'structured_text': ['User_' + str(i % 100) + '_Category_' + str(i % 3) for i in range(5)],+ 'email': [f'user{i}@example.com' for i in range(5)],+ 'mixed_text': [+ '[email protected]',+ 'JOHN DOE',+ 'phone: 123-456-7890',+ 'address: 123 Main St.',+ ]+ })++ # Comprehensive string operations+ result = (+ df.lazy()+ .with_columns([+ # Basic transformations+ pl.col('mixed_text').str.to_lowercase().alias('lowercase_text'),+ pl.col('structured_text').str.replace_all('_', ' ').alias('cleaned_text'),++ # Pattern extraction+ pl.col('structured_text').str.extract(r'Category_(\d+)', 1).alias('category_num'),+ pl.col('email').str.split('@').list.get(0).alias('email_username'),++ # Pattern matching+ pl.col('mixed_text').str.contains(r'@').alias('is_email'),+ pl.col('mixed_text').str.contains(r'\d{3}-\d{3}-\d{4}').alias('is_phone'),++ # Advanced replacements+ pl.col('mixed_text').str.replace(+ r'\d{3}-\d{3}-\d{4}',+ 'XXX-XXX-XXXX'+ ).alias('masked_phone'),++ # Categorical optimization for repeated values+ pl.col('structured_text').cast(pl.Categorical).alias('categorical_text')+ ])+ .collect()+ )+ result+ return df, pl, result+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-7.py b/marimo/_snippets/data/polars-7.pynew file mode 100644index 0000000000..6bac84138f--- /dev/null+++ b/marimo/_snippets/data/polars-7.py@@ -0,0 +1,71 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Advanced Grouping and Window Functions++ This snippet demonstrates advanced grouping operations in Polars using `group_by()`,+ window functions, and rolling computations for time series analysis.++ Example: `df.group_by('category').agg([pl.col('value').mean(), pl.col('value').rolling_mean(3)])`+ """+ )+ return+++def _():+ import polars as pl+ import numpy as np++ # Create sample data+ n_rows = 30+ df = pl.DataFrame({+ 'date': [(pl.datetime(2024, 1, 1) + pl.duration(days=x)) for x in range(n_rows)],+ 'category': ['A', 'B', 'C'] * 10,+ 'value': np.random.normal(10, 2, n_rows),+ 'quantity': np.random.randint(1, 100, n_rows)+ })++ # Advanced grouping and window operations+ result = (+ df.lazy()+ .with_columns([+ # Rolling average+ pl.col('value')+ .rolling_mean(window_size=3)+ .alias('rolling_avg'),+ # Cumulative sum+ pl.col('quantity')+ .cum_sum()+ .over('category')+ .alias('cumsum_by_category')+ ])+ .group_by('category')+ .agg([+ pl.col('value').mean().alias('avg_value'),+ pl.col('quantity').sum().alias('total_quantity')+ ])+ .sort('category')+ .collect()+ )+ result+ return df, n_rows, np, pl, result+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-8.py b/marimo/_snippets/data/polars-8.pynew file mode 100644index 0000000000..af3e063e4d--- /dev/null+++ b/marimo/_snippets/data/polars-8.py@@ -0,0 +1,63 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Missing Data and Data Quality++ This snippet demonstrates efficient handling of missing values, data validation,+ and type coercion in Polars.++ Example: `df.with_columns(pl.col('value').fill_null(pl.col('value').mean()))`+ """+ )+ return+++def _():+ import polars as pl+ import numpy as np++ # Create sample data with missing values+ df = pl.DataFrame({+ 'id': range(1000),+ 'category': ['A', 'B', None, 'C'] * 250,+ 'value': [1.5, None, 3.5, 4.5] * 250+ })++ # Data quality operations+ result = (+ df.lazy()+ .with_columns([+ pl.col('category').fill_null('Unknown').alias('category_clean'),+ pl.col('value').fill_null(pl.col('value').mean()).alias('value_clean'),+ pl.col('category').cast(pl.Categorical).alias('category_optimized')+ ])+ .collect()+ )++ # Calculate data quality metrics+ quality_metrics = {+ 'null_counts': df.null_count(),+ 'unique_categories': df.get_column('category').n_unique()+ }+ result, quality_metrics+ return df, np, pl, quality_metrics, result+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/data/polars-9.py b/marimo/_snippets/data/polars-9.pynew file mode 100644index 0000000000..324f6a648a--- /dev/null+++ b/marimo/_snippets/data/polars-9.py@@ -0,0 +1,66 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.11.0"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Polars: Reshaping Data++ This snippet demonstrates reshaping data in Polars using `pivot()` and `unpivot()`+ operations for transforming between wide and long formats.++ Example: `df.pivot(values="value", index=["date"], on="category")`+ """+ )+ return+++def _():+ import polars as pl+ import numpy as np++ # Create sample data+ df = pl.DataFrame(+ {+ "date": ["2024-01-01"] * 4 + ["2024-01-02"] * 4,+ "category": ["A", "B"] * 4,+ "metric": ["sales", "profit"] * 4,+ "value": np.random.randint(100, 1000, 8),+ }+ )++ # Reshaping operations+ # 1. Pivot wider+ pivoted = df.pivot(+ values="value",+ index=["date", "category"],+ on="metric",+ aggregate_function="first",+ )++ # 2. Unpivot longer+ unpivoted = pivoted.unpivot(+ index=["date", "category"],+ on=["sales", "profit"],+ value_name="value",+ variable_name="metric",+ )+ unpivoted+ return df, np, pivoted, pl, unpivoted+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_snippets/snippets.py b/marimo/_snippets/snippets.pyindex 0dc28cb627..053c77012c 100644--- a/marimo/_snippets/snippets.py+++ b/marimo/_snippets/snippets.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Awaitable, Generator, List, Optional@@ -77,16 +79,28 @@ def should_ignore_code(code: str) -> bool:def get_title_from_code(code: str) -> str:if not code:return ""+ code = code.strip()+ if not code.startswith("mo.md") and not code.startswith("#"):+ return ""if "# " in code:- # title is the start of # and end of \n+ # title is the start of # and end of \n or end quotestart = code.find("#")- end = code[start:].find("\n")- return code[start : end + start].replace("#", "", 1).strip()+ if "\n" in code[start:]:+ end = code[start:].find("\n")+ return code[start : end + start].replace("#", "", 1).strip()+ # No newline, find end quote+ if '"' in code[start:]:+ end = code[start:].find('"')+ return code[start : end + start].replace("#", "", 1).strip()+ if "'" in code[start:]:+ end = code[start:].find("'")+ return code[start : end + start].replace("#", "", 1).strip()+ return code[start:].replace("#", "", 1).strip()return ""def is_markdown(code: str) -> bool:- return code.startswith("mo.md")+ return code.strip().startswith("mo.md")def read_snippet_filenames_from_config() -> Generator[str, Any, None]:@@ -102,7 +116,7 @@ def read_snippet_filenames_from_config() -> Generator[str, Any, None]:def read_snippet_filenames(include_default_snippets: bool, custom_paths: List[str]) -> Generator[str, Any, None]:- paths = []+ paths: list[Path] = []if include_default_snippets:paths.append(import_files("marimo") / "_snippets" / "data")if custom_paths:diff --git a/tests/_snippets/test_snippets.py b/tests/_snippets/test_snippets.pyindex 5b3b3f43dd..ef317b3336 100644--- a/tests/_snippets/test_snippets.py+++ b/tests/_snippets/test_snippets.py@@ -14,7 +14,8 @@ async def test_snippets() -> None:snippets = await read_snippets()assert len(snippets.snippets) > 0# All have titles- assert all(s.title for s in snippets.snippets)+ for s in snippets.snippets:+ assert s.title# All have more than one sectionassert all(len(s.sections) > 1 for s in snippets.snippets)# All have a code section@@ -47,20 +48,31 @@ def test_get_title_from_code_with_non_title_hashes() -> None:assert get_title_from_code(code) == ""+def test_get_title_from_code_with_mo_md() -> None:+ code = "mo.md('# This is a title')"+ assert get_title_from_code(code) == "This is a title"+ code = 'mo.md("# This is a title")'+ assert get_title_from_code(code) == "This is a title"+ code = 'mo.md(r"""# This is a title""")'+ assert get_title_from_code(code) == "This is a title"++@pytest.mark.xfail(condition=is_windows(), reason="flaky on Windows")@pytest.mark.parametrize(("include_default_snippets", "custom_paths", "expected_snippets"),[- (True, [], 38),+ (True, [], 89),(False, [], 0),- (True, ["/notarealdirectory"], 38),+ (True, ["/notarealdirectory"], 89),(False, ["/notarealdirectory"], 0),- (False, ["marimo/_snippets/data"], 38),- (False, ["marimo/_snippets/data", "/notarealdirectory"], 38),+ (False, ["marimo/_snippets/data"], 89),+ (False, ["marimo/_snippets/data", "/notarealdirectory"], 89),],)def test_read_snippet_filenames(- include_default_snippets, custom_paths, expected_snippets+ include_default_snippets: bool,+ custom_paths: list[str],+ expected_snippets: int,) -> None:filenames = list(read_snippet_filenames(include_default_snippets, custom_paths)