抱歉,如果我的问题没有多大意义。我在 python 方面没有太多经验。
我有一些代码看起来像:
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]))
它失败并出现错误:
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'
看来我的list[Event]
已经不再是里面的了df
。我不知道如何让它发挥作用。
您可以通过传递来保留 Event 对象
return_dtype=pl.Object