3

我对大熊猫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在这种微不足道的情况下会失败。

4

1 回答 1

1

使用dayfirstto_datetime

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
于 2018-04-26T01:10:25.990 回答