Pandas。到目前为止()自动转换为<M8[ns],无法使用努比·伊斯纳特()

2024-10-03 15:25:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,它被读取为一个字符串,包含格式为“YYYY-MM-DD”的日期。我已使用将列转换为datetimepd.to\ U日期时间(使用强制)我打算使用努比·伊斯纳特(). 你知道吗

defaultDate = datetime.datetime(2020, 12, 31)
df['dates'] = pd.to_datetime(df['dates'], errors = 'coerce')
df['newDates'] = [x if ~np.isnat(x) else defaultDate for x in df['dates']]

当我试图运行代码时,出现了错误:

**TypeError**: ufunc 'isnat' is only defined for datetime and timedelta.

后来我发现列的数据类型已转换为<;M8[ns]。有没有一种方法可以正确地转换为datetime,或者有什么方法可以绕过这个问题?我有numpy版本1.16.4。你知道吗


Tags: to数据方法字符串dffordatetime格式
2条回答

看起来isnat是用来测试如下数组的:

In [47]: np.array([0,1,'NaT'], 'datetime64[D]')                                 
Out[47]: array(['1970-01-01', '1970-01-02',        'NaT'], dtype='datetime64[D]')
In [48]: np.isnat(_)                                                            
Out[48]: array([False, False,  True])

我必须通过实验来找出如何生成NaT元素。可能还有其他方法。你知道吗

您能否给出一个数据帧或序列,其中包含有效日期和非日期的样本值。这将使探索过滤方法变得更容易。我相信熊猫有某种非时间元素,但我不知道它是否与numpy元素兼容。还要记住,当Series元素包含string和pandas时,pandas很容易切换到object dtype。你知道吗

测试系列:

In [50]: ds = pd.Series(_47)                                                    
In [51]: ds                                                                     
Out[51]: 
0   1970-01-01
1   1970-01-02
2          NaT
dtype: datetime64[ns]
In [52]: ds.isna()                                                              
Out[52]: 
0    False
1    False
2     True
dtype: bool
In [54]: ds.isnull()                                                            
Out[54]: 
0    False
1    False
2     True
dtype: bool

更改序列的元素:

In [58]: ds[2]=12                                                               
In [59]: ds                                                                     
Out[59]: 
0    1970-01-01 00:00:00
1    1970-01-02 00:00:00
2                     12
dtype: object

改变了数据类型

In [60]: ds.values                                                              
Out[60]: 
array([Timestamp('1970-01-01 00:00:00'), Timestamp('1970-01-02 00:00:00'),
       12], dtype=object)
In [61]: np.isnat(_)                                                            
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-61-47ce91c66a51> in <module>
  > 1 np.isnat(_)

TypeError: ufunc 'isnat' is only defined for datetime and timedelta.

可能的转换顺序:

包含日期和其他内容的系列,对象数据类型:

In [118]: ds                                                                    
Out[118]: 
0    1970-01-01 00:00:00
1    1970-01-02 00:00:00
2                     12
dtype: object
In [119]: ds1=pd.to_datetime(ds,errors='coerce')                                
In [120]: ds1                                                                   
Out[120]: 
0   1970-01-01
1   1970-01-02
2          NaT
dtype: datetime64[ns]

强制转换产生NaT

In [121]: idx = np.isnat(ds1)                                                   
In [122]: idx                                                                   
Out[122]: 
0    False
1    False
2     True
dtype: bool
In [123]: ds1[idx]                                                              
Out[123]: 
2   NaT
dtype: datetime64[ns]

定义正确的默认值;它的数据类型很重要,因为pandas很容易更改数据类型(numpy不会):

In [124]: default= np.array('2020-12-31','datetime64[ns]')[()]                  
In [125]: default                                                               
Out[125]: numpy.datetime64('2020-12-31T00:00:00.000000000')
In [126]: ds1[idx]=default                                                      
In [127]: ds1                                                                   
Out[127]: 
0   1970-01-01
1   1970-01-02
2   2020-12-31
dtype: datetime64[ns]

<M8[ns]datetime64[ns]的同义词。此外,如果您正在与熊猫打交道,则不需要np.isnat

defaultDate = pd.to_datetime('2020-12-31')
df['newDates'] = [x if ~np.isnat(x) else defaultDate for x in df['dates']]
df['newDates'] = df['dates'].fillna(defaultDate)

相关问题 更多 >