简体   繁体   English

熊猫DataFrame日期系列到列表的转换

[英]Pandas DataFrame Date Series to List conversion

I have a dataframe called "signal_data" that has data as below 我有一个名为“ signal_data”的数据框,其数据如下

Pressure   DateTime             Temp
3025       2016-04-01 00:17:00  TTY    
3019       2016-04-01 00:17:00  TTY    
3019       2016-04-01 00:17:00  TTY    
.....          
3025       2016-05-01 10:17:00  TTY    
.....

I am trying to get unique values from DateTime column and convert to list. 我想从DateTime列中获取唯一值并将其转换为列表。 When I apply the following command, the datetime values are getting converted to int but not datetime. 当我应用以下命令时,datetime值将转换为int而不是datetime。

signal_data['DateTime'].unique().tolist()

[1459469820000000000,    
 1459516620000000000,    
 1459527420000000000,    
 ...    
 1462087020000000000]

May I know why this is happening and how to resolve this issue? 我可以知道为什么发生这种情况以及如何解决此问题吗?

When you call unique() , it returns a numpy array of type datetime. 调用unique() ,它将返回类型为datetime的numpy数组。 Numpy datetime is not python's fundamental datatype. Numpy datetime不是python的基本数据类型。 When you convert it to list it trys to change the datatype to pythonic version. 当您将其转换为列表时,它会尝试将数据类型更改为pythonic版本。 So you get the int. 这样就得到了int。 So use list(..) to keep the datetime as is. 因此,请使用list(..)保持日期时间不变。 ie

list(df['DateTime'].unique()) 
[numpy.datetime64('2016-04-01T00:17:00.000000000')]

OR convert it to series and then tolist()

pd.Series(df['DateTime'].unique()).tolist()
[Timestamp('2016-04-01 00:17:00')]

I'm not really sure why Pandas is implicity casting it. 我不太确定为什么Pandas会隐式转换它。 However, you can fix it by doing the following (assuming you have done import pandas as pd ): 但是,您可以通过执行以下操作来解决此问题(假设您已经import pandas as pd ):

pd.to_datetime(signal_data['DateTime'].unique()).tolist()

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

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