【问题标题】:Changing certain column type to date from datetime将某些列类型从日期时间更改为日期
【发布时间】:2022-01-11 13:23:02
【问题描述】:

我有一个df,我想在其中将某些列类型从datetime 更改为date

field   category    2022-01-10 00:00:00     2022-01-17 00:00:00     2022-01-24 00:00:00
A       10          500                     700                     500
B       15          60                      70                      50

我正在努力实现这一目标:

field   category    2022-01-10      2022-01-17      2022-01-24
A       10          500             700             500
B       15          60              70              50

因为在与其他df 连接期间,列类型从2021-11-19 更改为2021-11-19 00:00:00

来自this answer 我试过了::

df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : pd.to_datetime('2022-06-20 00:00:00')].columns = 
                                                 pd.to_datetime(df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : 
                                                 pd.to_datetime('2022-06-20 00:00:00')].columns)
                                                 .strftime('%Y-%m-%d')

但这并没有改变我无法理解的列的类型,因为

pd.to_datetime(df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : pd.to_datetime('2022-06-20 00:00:00')].columns).strftime('%Y-%m-%d')

返回:

Index(['2022-01-10', '2022-01-17', '2022-01-24')]

【问题讨论】:

  • 这里好像有列标题,和列类型不一样,能否提供数据示例beforeconcat
  • 其他df是否也包含日期时间列标题?
  • 好地方,其他df 包含字符串。

标签: python pandas datetime


【解决方案1】:

在您的列索引中,您混合了字符串(“字段”和“类别”)和时间戳(其他列),因此您的列索引是 Index 而不是 DatetimeIndex

>>> df.columns
Index([            'field',          'category', 2022-01-10 00:00:00,
       2022-01-17 00:00:00, 2022-01-24 00:00:00],
      dtype='object')

>>> [type(c) for c in df.columns]
[str,
 str,
 pandas._libs.tslibs.timestamps.Timestamp,
 pandas._libs.tslibs.timestamps.Timestamp,
 pandas._libs.tslibs.timestamps.Timestamp]

Timestamp 的默认字符串表示为YYYY-mm-dd HH:MM:SS,而DatetimeIndex 的每个值的默认表示只能是YYYY-mm-dd(如果可能)。

要获取日期格式,您必须将 Timestamp 转换为字符串。

【讨论】:

    【解决方案2】:

    鉴于此,特定的列类型是日期时间。 您可以使用 pandas 的 dt.date 仅保留日期。 请看下面的例子。

    dates_only = df["datetime"].dt.date
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2020-04-26
      • 2015-01-21
      相关资源
      最近更新 更多