带有日期(或日期时间)的熊猫“类型”

时间:2020-04-20 19:23:40

标签: python pandas date

This answer包含一种非常优雅的方式,可将所有类型的pandas列设置为一行:

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

不幸的是,我开始认为这种方法的应用受到限制,您迟早需要在多种行中使用多种其他方法来转换列类型。我测试了'category'并成功了,所以它将使用实际的python类型(例如intcomplex),然后用引号将'category'括起来的pandas术语。

我有一列日期如下:

25.07.10
08.08.10
07.01.11

我在this answer中看到了有关转换日期列的信息,但它们似乎都不适合上面的优雅语法。

我尝试过:

from datetime import date
df = df.astype({"date": date})

但是它给出了一个错误:

TypeError: dtype '<class 'datetime.date'>' not understood

(省略了整个跟踪)

我还尝试了pd.Series.dt.date,该方法也无效。 是否可以像这样将所有列(包括date或datetime列)强制转换为一行?

1 个答案:

答案 0 :(得分:0)

已在评论中回答以下问题,并指出以下作品:

df.astype({'date': 'datetime64[ns]'})

此外,您可以在读取数据时设置dtype:

pd.read_csv('path/to/file.csv', parse_dates=['date'])