Pandas: 类型 str 的列在使用 apply 函数后转换为 tslib.Timestamp

Pandas: column of type str converted to tslib.Timestamp after using apply function

当发生奇怪的事情时,我试图过滤掉数据框中的一些重复数据:'Col1' 字符串元素在没有通知的情况下被转换为时间戳。我希望 Col1 继续具有字符串元素。

示例如下:

>>> from pandas import *
>>> import datetime as DT
>>> df = DataFrame({
     'Col0': 'RR0 RR1 RR2 RR3 RR4 RR5 RR6 RR7'.split(),
     'Col1' : 'A7 A1 A2 A3 A4 A5 A6 A7'.split(),
     'Col2' : [
               DT.datetime(2013,1,1,13,0),
               DT.datetime(2013,1,1,13,5),
               DT.datetime(2013,10,1,20,0),
               DT.datetime(2013,10,2,10,0),
               DT.datetime(2013,10,1,20,0),
               DT.datetime(2013,10,2,10,0),
               DT.datetime(2013,12,2,12,0),
               DT.datetime(2013,12,2,14,0)
              ],
     'Col3': [1,3,5,1,8,1,9,3],
     'Col4': 'L0 L1 L0 L0 L2 L2 L3 L4'.split()})

>>> df=df[['Col0','Col1','Col2','Col3','Col4']]

>>> df
   Col0 Col1                Col2  Col3 Col4
0  RR0   A7 2013-01-01 13:00:00     1   L0
1  RR1   A1 2013-01-01 13:05:00     3   L1
2  RR2   A2 2013-10-01 20:00:00     5   L0
3  RR3   A3 2013-10-02 10:00:00     1   L0
4  RR4   A4 2013-10-01 20:00:00     8   L2
5  RR5   A5 2013-10-02 10:00:00     1   L2
6  RR6   A6 2013-12-02 12:00:00     9   L3
7  RR7   A7 2013-12-02 14:00:00     3   L4

# Filter the data of Col4 by oldest time register in Col2
>>> df2=df.groupby('Col4',group_keys=False,as_index=False).apply(lambda x: x.ix[x.Col2.idxmin()])

# df was filtered but Col1 was transformed to Timespan
>>> df2
   Col0       Col1                Col2  Col3 Col4
0  RR0 2015-04-07 2013-01-01 13:00:00     1   L0
1  RR1 2015-04-01 2013-01-01 13:05:00     3   L1
2  RR4 2015-04-04 2013-10-01 20:00:00     8   L2
3  RR6 2015-04-06 2013-12-02 12:00:00     9   L3
4  RR7 2015-04-07 2013-12-02 14:00:00     3   L4

问题:出现这种行为的原因是什么?有没有办法避免这种情况发生?

Pandas 尝试识别类似于日期时间的列数据,如果是,则将该列转换为日期时间数据类型。它在引擎盖下使用 dateutil.parser.parse 。不幸的是,dateutils.parser.parseA7 等字符串识别为日期:

In [28]: import dateutil.parser as DP
In [29]: DP.parse('A7')
Out[31]: datetime.datetime(2015, 4, 7, 0, 0)

即使(在这种情况下)它不是一个日期。

因此,要解决该问题,您可以使用 df.iloc:

df 收集 idxmin 和 select 行
idx = df.groupby('Col4')['Col2'].idxmin()
df2 = df.iloc[idx]

产量

  Col0 Col1                Col2  Col3 Col4
0  RR0   A7 2013-01-01 13:00:00     1   L0
1  RR1   A1 2013-01-01 13:05:00     3   L1
4  RR4   A4 2013-10-01 20:00:00     8   L2
6  RR6   A6 2013-12-02 12:00:00     9   L3
7  RR7   A7 2013-12-02 14:00:00     3   L4