【问题标题】:Pandas to_datetime has inconsistent behavior on non-american datesPandas to_datetime 在非美国日期的行为不一致
【发布时间】:2018-10-06 13:44:07
【问题描述】:

我对 pandas to_datetime 在非美国日期的行为感到困惑。

在这个简单的示例中,Pandas 正确推断了第 2 行和第 3 行的月份,但在第 1 行和第 4 行失败了。

显然它将第 2 行和第 3 行视为 dd/mm/yyyy 日期(因为 13 和 27 显然不能是月份),但将剩余日期视为 mm/dd/yyyy

我的期望是to_datetime 会从整个系列中推断出来,然后对每个条目都一视同仁。

import pandas as pd 
results = pd.DataFrame()

european_dates = pd.Series(['05/04/2007',   # <-- April 5th, 2007
                            '13/04/2006',   # <-- April 13th, 2006
                            '27/12/2014',   # <-- December 27th, 2014
                            '02/07/2010'])  # <-- July 2nd, 2010 

# note: the same happens with infer_datetime_format=False
inferred_dates = pd.to_datetime(european_dates,
                                infer_datetime_format=True) 

results['day'] = inferred_dates.dt.day
results['month'] = inferred_dates.dt.month
results['year'] = inferred_dates.dt.year

results

注意:我知道to_datetime 有一个dayfirst 参数和一个format 参数,我的问题主要是关于为什么infer_datetime_format 在这种微不足道的情况下会失败。

【问题讨论】:

    标签: python pandas datetime time-series string-to-datetime


    【解决方案1】:

    to_datetime 中使用dayfirst

    european_dates = pd.Series(['05/04/2007',   # <-- April 5th, 2007
                                '13/04/2006',   # <-- April 13th, 2006
                                '27/12/2014',   # <-- December 27th, 2014
                                '02/07/2010'])  # <-- July 2nd, 2010 
    inferred_dates = pd.to_datetime(european_dates,dayfirst =True) 
    results = pd.DataFrame()
    results['day'] = inferred_dates.dt.day
    results['month'] = inferred_dates.dt.month
    results['year'] = inferred_dates.dt.year
    results
    Out[109]: 
       day  month  year
    0    5      4  2007
    1   13      4  2006
    2   27     12  2014
    3    2      7  2010
    

    【讨论】:

    • 感谢您的回答,但正如我在原始问题中提到的,我知道dayfirstformat。问题是为什么infer_datetime_format 的行为不一致,而不是寻找解决方法。
    • @sapo_cosmico 因为 dayfirst 默认为 false,当第一个可以是月份时,它将转换为 m 而不是 d
    • 是的,你知道它是否有任何方法可以一致地推断? (即“如果不是所有的行都可以先有月份,那么它永远不可能是月份”
    • @sapo_cosmico rafer 到此链接stackoverflow.com/questions/46842793/…
    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多