为什么Pandas在聚合函数中将日期时间转换为float

2024-09-30 01:22:33 发布

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

更新帖子:

我想知道Pandas为什么要将datetime列转换为float列。在

下面的代码重现了我遇到的问题。在

df = pd.DataFrame(pd.date_range("2012-01-01", periods=12).values.reshape(3,4), columns=list('abcd'))

print "Original:", {col: df[col].dtype for col in df.columns}

df['c'].loc[1] = pd.NaT
df['d'].loc[1] = pd.NaT

df['ab'] = df[['a','b']].min(1)
df['cd'] = df[['c','d']].min(1)

print "New:", {col: df[col].dtype for col in df.columns}

打印:

^{pr2}$

注意,列abdtype('<M8[ns]')类型,而{}是{}类型。在

熊猫为什么要改变体型?在

原文:

我运行的代码非常简单:

x['new1'] = x[['startDate1','stopDate1']].min(1)
x['new2'] = x[['startDate2','stopDate2']].min(1)

其中x看起来像这样:

ID         startDate1    stopDate1    startDate2    stopDate2

0          2000-01-01   2000-03-05    2005-01-01   2006-03-05
               ...          ...          ...          ...
40053      1997-01-01   2011-03-05    2012-01-01   2012-03-05

对所有原始列运行x[colName].dtype,返回dtype('<M8[ns]')。在

然而,x['new1'].dtypex['new2'].dtype不匹配,前者是dtype('<M8[ns]'),后者是dtype('float64')。在

我已经用这条线修好了,但我想知道为什么会这样,因为这对我来说没有什么意义。在

x['new2'] = pd.to_datetime(x[['startDate2','stopDate2']].min(1))

有很多行,所以我不能全部都看一遍。这意味着startDate2stopDate2列有什么意义?

更新原始帖子: 我发现这些列之间的唯一区别是stopDate2至少有一行带有NaT。删除NaT可以消除这个问题,但是我不能用伪数据重现它。在


Tags: columns代码dfdatetimecolminnat帖子
2条回答

相关问题。使用熊猫0.18.1。请注意,df.timestamp在两种不同的场景中具有不同的类型:

df = pd.DataFrame(np.random.rand(250).reshape(50,5), 
                      index=pd.date_range('1/1/2016', periods=50, freq='H' ),
                      columns=list('ABCDE'))
df['timestamp'] = df.index

print(df.timestamp.resample('30min',label='right').last().head(3))
print('==========')
print(df.timestamp.resample('2H',label='right').last().head(3))

输出:

^{pr2}$

还发现了与此问题相关的错误报告: https://github.com/pydata/pandas/issues/12941

正如评论中所说,这可能是一个bug,由于存在NaN,如果您想解决问题,可以执行以下操作:

df[["c", "d"]].min(axis=1).astype("<M8[ns]")

相关问题 更多 >

    热门问题