Issue
I have a Polars df with a column 'Checkout Time' in a string format, e.g '17:54'.
I'm converting to a time format with:
df = df.with_columns(pl.col('Checkout Time').str.to_time('%H:%M'))
How would I then get the actual hour of the time as an integer?
I could do it with map_rows but is there a better way than this?
df.with_columns(
df.select('Checkout Time').map_rows(lambda x: x[0].hour)
).rename({'map': 'Hour'})
But this seems annoying, is there a way to do it directly in with_columns?
Some example data:
data = np.array(['06:30', '17:45', '18:32'])
df = pl.from_numpy(data, schema=["Checkout Time"])
df = df.with_columns(pl.col('Checkout Time').str.to_time('%H:%M'))
Solution
You can use polars.Expr.dt.hour
directly:
import polars as pl
import numpy as np
data = np.array(['06:30', '17:45', '18:32'])
df = pl.from_numpy(data, schema=["Checkout Time"])
df = df.with_columns(pl.col('Checkout Time').str.to_time('%H:%M'))
df = df.with_columns(Hour=pl.col('Checkout Time').dt.hour())
>>> df shape: (3, 2) ┌───────────────┬──────┐ │ Checkout Time ┆ Hour │ │ --- ┆ --- │ │ time ┆ i8 │ ╞═══════════════╪══════╡ │ 06:30:00 ┆ 6 │ │ 17:45:00 ┆ 17 │ │ 18:32:00 ┆ 18 │ └───────────────┴──────┘
Answered By - FJSevilla
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.