最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to materialize Polars expression into Series? - Stack Overflow

programmeradmin1浏览0评论

Working with a single series instead of a dataframe, how can I materialize an expression on that series? For instance, when I run

time = pl.Series([pl.datetime(2025, 3, 27)])
(time + pl.duration(minutes=5)).to_numpy()

I get

AttributeError                            Traceback (most recent call last)
Cell In[46], line 2
      1 time = pl.Series([pl.datetime(2025, 3, 27)])
----> 2 (time + pl.duration(minutes=5)).to_numpy()

AttributeError: 'Expr' object has no attribute 'to_numpy'

Working with a single series instead of a dataframe, how can I materialize an expression on that series? For instance, when I run

time = pl.Series([pl.datetime(2025, 3, 27)])
(time + pl.duration(minutes=5)).to_numpy()

I get

AttributeError                            Traceback (most recent call last)
Cell In[46], line 2
      1 time = pl.Series([pl.datetime(2025, 3, 27)])
----> 2 (time + pl.duration(minutes=5)).to_numpy()

AttributeError: 'Expr' object has no attribute 'to_numpy'
Share Improve this question edited Mar 27 at 21:18 jqurious 22k5 gold badges20 silver badges39 bronze badges asked Mar 27 at 20:55 mwlonmwlon 1,0189 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You need a "DataFrame" to run expressions.

Your example is "wrong" because passing an Expr creates a Series with dtype object.

pl.Series([pl.datetime(2025, 3, 27)])
# shape: (1,)
# Series: '' [o][object]
# [
#   2025-03-27 00:00:00.alias("datetime")
# ]
# 

pl.select() is shorthand for creating an empty frame.

s = pl.select(pl.datetime(2025, 3, 27)).to_series()
# shape: (1,)
# Series: 'datetime' [datetime[μs]]
# [
#   2025-03-27 00:00:00
# ]
pl.select(s + pl.duration(minutes=5))
shape: (1, 1)
┌─────────────────────┐
│ datetime            │
│ ---                 │
│ datetime[μs]        │
╞═════════════════════╡
│ 2025-03-27 00:05:00 │
└─────────────────────┘

You can add .to_series() if you want to go back to a Series.

There is also a Series method to do this without expressions.

  • .dt.offset_by()
s.dt.offset_by("5m")
# shape: (1,)
# Series: 'datetime' [datetime[μs]]
# [
#   2025-03-27 00:05:00
# ]
发布评论

评论列表(0)

  1. 暂无评论