删除dtype datetime NaT [英] Remove dtype datetime NaT

查看:101
本文介绍了删除dtype datetime NaT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在准备要输出的pandas df,并且想要删除表格中的NaN和NaT,并将这些表格的位置留为空白.一个例子是

I am preparing a pandas df for output, and would like to remove the NaN and NaT in the table, and leave those table locations blank. An example would be

mydataframesample 

col1    col2     timestamp
a       b        2014-08-14
c       NaN      NaT

将成为

col1    col2     timestamp
a       b        2014-08-14
c       

大多数值是dtypes对象,其timestamp列为datetime64 [ns].为了解决此问题,我尝试使用熊猫的mydataframesample.fillna(' ')有效地在该位置留出空间.但是,这不适用于datetime类型.为了解决这个问题,我试图将timestamp列转换回对象或字符串类型.

Most of the values are dtypes object, with the timestamp column being datetime64[ns]. In order to fix this, I attempted to use panda's mydataframesample.fillna(' ') to effectively leave a space in the location. However, this doesn't work with the datetime types. In order to get around this, I'm trying to convert the timestamp column back to object or string type.

是否可以在不进行类型转换的情况下删除NaN/NaT?如果没有,我该如何进行类型转换(尝试使用str()和astype(str),但很难将日期时间作为原始格式)?

Is it possible to remove the NaN/NaT without doing the type conversion? If not, how do I do the type conversion (tried str() and astype(str) but difficulty with datetime being the original format)?

推荐答案

这不会赢得任何速度方面的奖励,但是如果DataFrame不太长,则使用列表推导进行重新分配即可完成这项工作:

This won't win any speed awards, but if the DataFrame is not too long, reassignment using a list comprehension will do the job:

df1['date'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in df1['date']]


import numpy as np
import pandas as pd
Timestamp = pd.Timestamp
nan = np.nan
NaT = pd.NaT
df1 = pd.DataFrame({
    'col1': list('ac'),
    'col2': ['b', nan],
    'date': (Timestamp('2014-08-14'), NaT)
    })

df1['col2'] = df1['col2'].fillna('')
df1['date'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in df1['date']]

print(df1)

收益

  col1 col2        date
0    a    b  2014-08-14
1    c                 

这篇关于删除dtype datetime NaT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆