大熊猫最大的日期?

时间:2017-09-14 18:16:16

标签: python pandas datetime dataframe max

遗憾的是,here问题的解决方案无法解决此问题。我使用的是Python 3.6.2

数据框, public partial class aplicaciones { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public aplicaciones() { this.appNfam = new HashSet<appNfam>(); } public int id { get; set; } public string nombre { get; set; } public string icon { get; set; } public string img { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<appNfam> appNfam { get; set; } }

df

重现问题:

                            date1                        date2
rec0    2017-05-25 14:02:23+00:00    2017-05-25 14:34:43+00:00
rec1                          NaT    2017-05-16 19:37:43+00:00

上述两个列均已使用import psycopg2 import pandas as pd Timestamp = pd.Timestamp NaT = pd.NaT df = pd.DataFrame({'date1': [Timestamp('2017-05-25 14:02:23'), NaT], 'date2': [Timestamp('2017-05-25 14:34:43'), Timestamp('2017-05-16 19:37:43')]}) tz = psycopg2.tz.FixedOffsetTimezone(offset=0, name=None) for col in ['date1', 'date2']: df[col] = pd.DatetimeIndex(df[col]).tz_localize(tz) print(df.max(axis=1)) 进行转换,以获得以下列类型:pd.to_datetime()

运行datetime64[ns, psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)]并不会出错,但肯定会提供错误的解决方案。

输出(不正确):

df.max(axis=1)

我现有的修复方法是rec0 NaN rec1 NaN dtype: float64 df的自定义函数,如下所示:

apply

输出(正确):

def get_max(x):
    test = x.dropna()
    return max(test)
df.apply(get_max,axis=1)

可能rec0 2017-05-25 14:34:43+00:00 rec1 2017-05-16 19:37:43+00:00 dtype: datetime64[ns, psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)] 没有处理日期对象,但只查找浮点数(docs)。 知道为什么df.max()只返回df.max(axis=1)

2 个答案:

答案 0 :(得分:0)

经过一些测试后,pandaspsycopg2.tz.FixedOffsetTimezone似乎出现了问题。

如果您尝试df.max(axis=0),它会按预期工作,但在您指出df.max(axis=1)时会返回一系列NaN。 如果您未将psycopg2.tz.FixedOffsetTimezone用作tz,则df.max(axis=1)将返回预期结果。

在这种情况下,其他操作将失败,例如df.transpose

请注意,如果您尝试df.values.max(axis=1),您将获得预期的结果。所以numpy.array似乎能够解决这个问题。 您应该搜索pandas Github问题(like this one),如果找不到解决方案,可以考虑开一个新问题。

另一个解决方案是删除psycopg2.tz.FixedOffsetTimezone,但您可能有理由专门使用此功能。

答案 1 :(得分:0)

在Python 3.8中使用Pandas 1.0.5 我仍然得到一系列的Nans。通过将两列都转换为日期时间,然后向max()函数添加skipna = True和numeric_only = False来解决此问题:

df['1'] = pd.to_datetime(df['1'], utc=True)
df['2'] = pd.to_datetime(df['2'], utc=True) 
df['3'] = df[['1', '2']].max(axis=1, skipna=True, numeric_only=False)
相关问题