Desculpe se minha pergunta não faz muito sentido. Não tenho muita experiência em python.
Eu tenho um código que se parece com:
import polars as pl
from typing import NamedTuple
class Event(NamedTuple):
name: str
description: str
def event_table(num) -> list[Event]:
events = []
for i in range(5):
events.append(Event("name", "description"))
return events
def pretty_string(events: list[Event]) -> str:
pretty = ""
for event in events:
pretty += f"{event.name}: {event.description}\n"
return pretty
# This does work
print(pretty_string(event_table(5)))
# But then it doesn't work if I have my `list[Event]` in a dataframe
data = {"events": [0, 1, 2, 3, 4]}
df = pl.DataFrame(data).select(events=pl.col("events").map_elements(event_table))
# This doesn't work
pretty_df = df.select(events=pl.col("events").map_elements(pretty_string))
print(pretty_df)
# Neither does this
print(pretty_string(df["events"][0]))
Falha com erro:
Traceback (most recent call last):
File "path/to/script.py", line 32, in <module>
pretty_df = df.select(events=pl.col("events").map_elements(pretty_string))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "path/to/.venv/lib/python3.11/site-packages/polars/dataframe/frame.py", line 8116, in select
return self.lazy().select(*exprs, **named_exprs).collect(_eager=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "path/to/.venv/lib/python3.11/site-packages/polars/lazyframe/frame.py", line 1934, in collect
return wrap_df(ldf.collect())
^^^^^^^^^^^^^
polars.exceptions.ComputeError: AttributeError: 'dict' object has no attribute 'name'
Parece que o meu list[Event]
não está mais tão dentro do arquivo df
. Não tenho certeza de como fazer isso funcionar.
Você pode manter os objetos Event passando
return_dtype=pl.Object