过滤掉Python DataFram中格式不正确的datetime值

2024-10-03 09:20:50 发布

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

我有一个数据框,其中一列存储日期。你知道吗

但是,其中一些日期是格式正确的datetime对象,如'2018-12-24 17:00:00',而另一些则不是,并且存储为'20181225'。你知道吗

当我尝试使用plotly绘制这些时,格式不正确的值变成了EPOCH日期,这是一个问题。你知道吗

有没有什么办法我可以得到一个数据帧的副本,只有那些行的日期格式正确?你知道吗

我试过用

clean_dict= dailySum_df.where(dailySum_df[isinstance(dailySum_df['time'],datetime.datetime)])

方法,但由于“Array conditional must be same shape as self”错误而无法工作。你知道吗

    dailySum_df = pd.DataFrame(list(cursors['dailySum']))

    trace = go.Scatter(
        x=dailySum_df['time'],
        y=dailySum_df['countMessageIn']

    )
    data = [trace]
    py.plot(data, filename='basic-line')

Tags: 数据对象cleandfdatadatetimetime格式
2条回答

尝试使用解析数据帧的dates列dateutil.parser.parse文件应用函数。你知道吗

enter image description here

应用dateutil.parser,另请参阅我的答案here

import dateutil.parser as dparser
def myparser(x):
    try:
       return dparser.parse(x)
    except:
       return None

df = pd.DataFrame( {'time': ['2018-12-24 17:00:00', '20181225', 'no date at all'], 'countMessageIn': [1,2,3]})
df.time = df.time.apply(myparser)
df = df[df.time.notnull()]

输入:

                  time  countMessageIn
0  2018-12-24 17:00:00               1
1             20181225               2
2       no date at all               3

输出:

                 time  countMessageIn
0 2018-12-24 17:00:00               1
1 2018-12-25 00:00:00               2

与Gustavo的解决方案不同,它可以处理没有可识别日期的行,并根据您的问题过滤掉这些行。你知道吗

如果原始时间列可能包含日期本身以外的其他文本,请包含fuzzy=True参数,如here所示。你知道吗

相关问题 更多 >