简体   繁体   English

Pandas 'astype' 带日期(或日期时间)

[英]Pandas 'astype' with date (or datetime)

This answer contains a very elegant way of setting all the types of your pandas columns in one line:这个答案包含一种非常优雅的方式,可以在一行中设置 pandas 列的所有类型:

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

I am starting to think that that unfortunately has limited application and you will have to use various other methods of casting the column types sooner or later, over many lines.我开始认为,不幸的是,它的应用有限,您迟早将不得不使用各种其他方法在多行中转换列类型。 I tested 'category' and that worked, so it will take things which are actual python types like int or complex and then pandas terms in quotation marks like 'category' .我测试了'category'并且有效,因此它将采用实际 python 类型(如intcomplex ),然后是 pandas 术语,如'category'

I have a column of dates which looks like this:我有一列日期,如下所示:

25.07.10
08.08.10
07.01.11

I had a look at this answer about casting date columns but none of them seem to fit into the elegant syntax above.我看了一下这个关于转换日期列的答案,但它们似乎都不适合上面的优雅语法。

I tried:我试过了:

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

but it gave an error:但它给出了一个错误:

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

(whole trace omitted) (全迹省略)

I also tried pd.Series.dt.date which also didn't work.我也试过pd.Series.dt.date也没有用。 Is it possible to cast all your columns including the date or datetime column in one line like this?是否可以像这样在一行中投射所有列,包括日期或日期时间列?

This has been answered in the comments where it was noted that the following works:这已在评论中得到回答,其中指出以下工作:

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

In addition, you can set the dtype when reading in the data:另外,你可以在读入数据时设置dtype:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM