Skip to content

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.

fix: include datatime and timedelta index in output (#1242)

Myles Scolnick03934cf315c4
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 2c576fbbd6..84ac0d22f5 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -77,6 +77,33 @@ class PandasTableManagerFactory(TableManagerFactory):
name = str(index.name) if index.name else ""
return [(name, index.tolist())] # type: ignore[list-item]
+ if isinstance(index, pd.DatetimeIndex):
+ # Format to Y-m-d if the time is 00:00:00
+ formatted: list[str] = index.strftime(
+ "%Y-%m-%d %H:%M:%S"
+ ).tolist()
+ if all(time.endswith(" 00:00:00") for time in formatted):
+ return [
+ (
+ index.name or "",
+ index.strftime("%Y-%m-%d").tolist(),
+ )
+ ]
+ return [
+ (
+ index.name or "",
+ index.strftime("%Y-%m-%d %H:%M:%S").tolist(),
+ )
+ ]
+
+ if isinstance(index, pd.TimedeltaIndex):
+ return [
+ (
+ index.name or "",
+ index.astype(str).tolist(),
+ )
+ ]
+
return []
def get_field_types(self) -> FieldTypes:
diff --git a/marimo/_smoke_tests/bugs/1140.py b/marimo/_smoke_tests/bugs/1140.py
index cf03268a8f..cc01e35d50 100644
--- a/marimo/_smoke_tests/bugs/1140.py
+++ b/marimo/_smoke_tests/bugs/1140.py
@@ -1,7 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
+
import marimo
-__generated_with = "0.4.3"
+__generated_with = "0.4.5"
app = marimo.App(width="full")
@@ -15,46 +16,84 @@ def __():
@app.cell
def __(mo):
- mo.md("""
+ mo.md(
+ """
This highlights some of the differences between displaying data in different libraries: polars, pandas, pyarrow, and dictionaries.
These differences are due to how each library prints their data as CSVs.
- """)
+ """
+ )
return
@app.cell
def __(np, pd):
data = {
- 'Integer': [1, 2, 3],
- 'Float': [1.0, 2.5, 3.5],
- 'String': ['apple', 'banana', 'cherry'],
- 'Boolean': [True, False, True],
- 'LargeInt': np.array([1e12, 2e12, 3e12], dtype=np.int64),
- 'LargeFloat': np.array([1.234567890123456789, 2.234567890123456789, 3.234567890123456789], dtype=np.float64),
- 'DateTime': pd.to_datetime(['2021-01-01', '2021-06-01', '2021-09-01']),
- 'Timedelta': pd.to_timedelta(['1 days', '2 days', '3 days']),
- 'Categorical': pd.Categorical(['test', 'train', 'test']),
- 'NumpyArray': [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([7, 8, 9])],
- 'Duration': pd.to_timedelta(['10:00:00', '15:30:00', '20:45:00']),
- 'Series': [pd.Series([1, 2, 3]), pd.Series([1, 2, 3]), pd.Series([1, 2, 3])],
- 'Nested': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}],
- 'Mixed': [1, 1.1, '1'],
- 'Mixed 2': [True, np.array([1, 2, 3]), pd.to_datetime('2021-01-01')],
- 'Null': [None, None, None],
- 'NaN': [np.nan, np.nan, np.nan],
- 'Infinity': [np.inf, np.inf, np.inf],
- 'Negative Infinity': [-np.inf, -np.inf, -np.inf],
- 'Zero': [0, 0, 0],
- 'Empty': ['', '', ''],
- 'Empty List': [[], [], []],
- 'Empty Dict': [{}, {}, {}],
- 'Set': [set(), set(["a", "b"]), set([1, 2])],
- 'Empty Tuple': [(), (), ()],
+ "Integer": [1, 2, 3],
+ "Float": [1.0, 2.5, 3.5],
+ "String": ["apple", "banana", "cherry"],
+ "Boolean": [True, False, True],
+ "LargeInt": np.array([1e12, 2e12, 3e12], dtype=np.int64),
+ "LargeFloat": np.array(
+ [1.234567890123456789, 2.234567890123456789, 3.234567890123456789],
+ dtype=np.float64,
+ ),
+ "DateTime": pd.to_datetime(["2021-01-01", "2021-06-01", "2021-09-01"]),
+ "Timedelta": pd.to_timedelta(["1 days", "2 days", "3 days"]),
+ "Categorical": pd.Categorical(["test", "train", "test"]),
+ "NumpyArray": [
+ np.array([1, 2, 3]),
+ np.array([4, 5, 6]),
+ np.array([7, 8, 9]),
+ ],
+ "Duration": pd.to_timedelta(["10:00:00", "15:30:00", "20:45:00"]),
+ "Series": [
+ pd.Series([1, 2, 3]),
+ pd.Series([1, 2, 3]),
+ pd.Series([1, 2, 3]),
+ ],
+ "Nested": [{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}],
+ "Mixed": [1, 1.1, "1"],
+ "Mixed 2": [True, np.array([1, 2, 3]), pd.to_datetime("2021-01-01")],
+ "Null": [None, None, None],
+ "NaN": [np.nan, np.nan, np.nan],
+ "Infinity": [np.inf, np.inf, np.inf],
+ "Negative Infinity": [-np.inf, -np.inf, -np.inf],
+ "Zero": [0, 0, 0],
+ "Empty": ["", "", ""],
+ "Empty List": [[], [], []],
+ "Empty Dict": [{}, {}, {}],
+ "Set": [set(), set(["a", "b"]), set([1, 2])],
+ "Empty Tuple": [(), (), ()],
}
return data,
+def __(pd):
+ df_with_date_index = pd.DataFrame(
+ {
+ "a": [1, 2, 3],
+ "b": [4, 5, 6],
+ "c": [7, 8, 9],
+ },
+ index=pd.to_datetime(["2021-01-01", "2021-06-01", "2021-09-01"]),
+ )
+ return df_with_date_index,
+
+
+def __(df_with_date_index, mo):
+ mo.ui.table(df_with_date_index, label="Pandas with date index")
+ return
+
+
+def __(df_with_date_index):
+ df_with_date_index
+ return
+
+
@app.cell
def __(df, mo):
mo.ui.table(df, label="Pandas")
@@ -76,7 +115,7 @@ def __(df, mo):
@app.cell
def __(df, mo):
- mo.ui.table(df.to_dict(orient='records'), label="List of dictionaries")
+ mo.ui.table(df.to_dict(orient="records"), label="List of dictionaries")
return
@@ -85,6 +124,7 @@ def __(data_2, mo, pd):
# Arrow
import pyarrow as pa
import pyarrow.parquet as pq
+
table = pa.Table.from_pandas(pd.DataFrame(data_2))
mo.ui.table(table, label="Pyarrow")
return pa, pq, table
@@ -93,13 +133,16 @@ def __(data_2, mo, pd):
@app.cell
def __(np, pd):
data_2 = {
- 'Integer': [1, 2, 3],
- 'Float': [1.0, 2.5, 3.5],
- 'String': ['apple', 'banana', 'cherry'],
- 'Boolean': [True, False, True],
- 'LargeInt': np.array([1e12, 2e12, 3e12], dtype=np.int64),
- 'LargeFloat': np.array([1.234567890123456789, 2.234567890123456789, 3.234567890123456789], dtype=np.float64),
- 'DateTime': pd.to_datetime(['2021-01-01', '2021-06-01', '2021-09-01']),
+ "Integer": [1, 2, 3],
+ "Float": [1.0, 2.5, 3.5],
+ "String": ["apple", "banana", "cherry"],
+ "Boolean": [True, False, True],
+ "LargeInt": np.array([1e12, 2e12, 3e12], dtype=np.int64),
+ "LargeFloat": np.array(
+ [1.234567890123456789, 2.234567890123456789, 3.234567890123456789],
+ dtype=np.float64,
+ ),
+ "DateTime": pd.to_datetime(["2021-01-01", "2021-06-01", "2021-09-01"]),
# Not support in polars
# 'Timedelta': pd.to_timedelta(['1 days', '2 days', '3 days']),
# 'Categorical': pd.Categorical(['test', 'train', 'test']),
@@ -110,12 +153,12 @@ def __(np, pd):
# 'Mixed': [1, 1.1, '1'],
# Mixed 2 is not supported in polars
# 'Mixed 2': [True, np.array([1, 2, 3]), pd.to_datetime('2021-01-01')],
- 'Null': [None, None, None],
- 'NaN': [np.nan, np.nan, np.nan],
- 'Infinity': [np.inf, np.inf, np.inf],
- 'Negative Infinity': [-np.inf, -np.inf, -np.inf],
- 'Zero': [0, 0, 0],
- 'Empty': ['', '', ''],
+ "Null": [None, None, None],
+ "NaN": [np.nan, np.nan, np.nan],
+ "Infinity": [np.inf, np.inf, np.inf],
+ "Negative Infinity": [-np.inf, -np.inf, -np.inf],
+ "Zero": [0, 0, 0],
+ "Empty": ["", "", ""],
# More nested not supported
# 'Empty List': [[], [], []],
# 'Empty Dict': [{}, {}, {}],
@@ -129,6 +172,7 @@ def __(np, pd):
def __(data_2, mo):
# Polars
import polars as pl
+
pl_df = pl.DataFrame(data_2)
mo.ui.table(pl_df, label="Polars")
return pl, pl_df
@@ -140,5 +184,10 @@ def __(pl_df):
return
+def __():
+ return
+
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 0b08e5e9ff..fef2b48fb1 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -48,6 +48,60 @@ class TestPandasTableManager(unittest.TestCase):
expected_headers = []
assert self.manager.get_row_headers() == expected_headers
+ def test_get_row_headers_date_index(self) -> None:
+ import pandas as pd
+
+ data = pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": [4, 5, 6],
+ "C": [7, 8, 9],
+ },
+ index=pd.to_datetime(["2021-01-01", "2021-06-01", "2021-09-01"]),
+ )
+ manager = self.factory.create()(data)
+ expected_headers = [
+ ("", ["2021-01-01", "2021-06-01", "2021-09-01"]),
+ ]
+ assert manager.get_row_headers() == expected_headers
+
+ def test_get_row_headers_timedelta_index(self) -> None:
+ import pandas as pd
+
+ data = pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": [4, 5, 6],
+ "C": [7, 8, 9],
+ },
+ index=pd.to_timedelta(["1 days", "2 days", "3 days"]),
+ )
+ manager = self.factory.create()(data)
+ expected_headers = [
+ ("", ["1 days", "2 days", "3 days"]),
+ ]
+ assert manager.get_row_headers() == expected_headers
+
+ def test_get_row_headers_multi_index(self) -> None:
+ import pandas as pd
+
+ data = pd.DataFrame(
+ {
+ "A": [1, 2, 3],
+ "B": [4, 5, 6],
+ "C": [7, 8, 9],
+ },
+ index=pd.MultiIndex.from_tuples(
+ [("a", 1), ("b", 2), ("c", 3)], names=["X", "Y"]
+ ),
+ )
+ manager = self.factory.create()(data)
+ expected_headers = [
+ ("X", ["a", "b", "c"]),
+ ("Y", [1, 2, 3]),
+ ]
+ assert manager.get_row_headers() == expected_headers
+
def test_is_type(self) -> None:
assert self.manager.is_type(self.data)
assert not self.manager.is_type("not a dataframe")