如何将极坐标日期时间列转换为字符串列?

问题描述 投票:0回答:3

我正在尝试使用 Polars 库将日期时间列更改为字符串列。我只想要新列上的日期:

import polars as pl

df
shape: (139878, 1)
┌─────────────────────┐
│ date_time           │
│ ---                 │
│ datetime[ns]        │
╞═════════════════════╡
│ 2007-04-19 00:00:00 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2007-05-02 00:00:00 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2007-05-03 00:00:00 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2007-05-03 00:00:00 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤

下面的解决方案包括时间,我只需要日期。

df.with_column(pl.col('date_time').cast(pl.Utf8))
shape: (14, 1)
┌───────────────────────────────┐
│ date_time                     │
│ ---                           │
│ str                           │
╞═══════════════════════════════╡
│ 2017-06-19 00:00:00.000000000 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2017-11-13 00:00:00.000000000 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2018-01-24 00:00:00.000000000 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2018-01-29 00:00:00.000000000 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
python dataframe data-manipulation python-polars
3个回答
1
投票

你应该尝试这个:

# Polars
df = df.with_columns(df['date_time'].dt.strftime('%Y-%m-%d'))

# Pandas
df['date_time'] = df['date_time'].dt.strftime('%Y-%m-%d')

编辑:添加了极坐标


0
投票

我最终得到了这个解决方法,但@ErnestBidouille 的答案更多的是我想要的。

import polars as pl

df = df.with_column(pl.col('date_time').cast(pl.Date).cast(pl.Utf8))

print(df)
shape: (14, 1)
┌────────────┐
│ date_time  │
│ ---        │
│ str        │
╞════════════╡
│ 2017-06-19 │
├╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2017-11-13 │
├╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2018-01-24 │
├╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2018-01-29 │
├╌╌╌╌╌╌╌╌╌╌╌╌┤

0
投票

顺便说一句,如果您想直接将日期时间对象转换为 Polars 中的数字,您可以尝试以下方法:

如“2023-06-01 00:00:00”-> 20230601

def date2num(df, col): df = df.with_columns( pl.col(col).dt.strftime('%Y%m%d').cast(pl.Int32).alias(col) ) 返回df

© www.soinside.com 2019 - 2024. All rights reserved.