Python中unicode错误的操作数类型不受支持

2024-09-27 21:33:43 发布

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

我有一个pandas数据帧,格式如下:

    Timestamp                     Clientip
    2015-07-22T02:40:06.499174Z   106.51.235.133    
    2015-07-22T02:40:06.632589Z   115.250.16.146

为了对上述数据进行会话化,我基于clientip对其进行分组,然后创建了一个sessionnumber字段。在

^{pr2}$

当我运行第二个命令时,我得到错误“unsupported operand type for-:'unicode'and'unicode'”

不知道是什么让事情不对。任何帮助都将不胜感激。在


Tags: 数据命令pandasfor格式type错误unicode
2条回答

试试这个:

In [162]: df
Out[162]:
                     Timestamp        Clientip
0  2015-07-22T02:40:06.499174Z  106.51.235.133
1  2015-07-22T02:50:06.000000Z  106.51.235.133
2  2015-07-22T02:40:06.632589Z  115.250.16.146
3  2015-07-22T03:30:16.111111Z  115.250.16.146

In [163]: df.Timestamp = pd.to_datetime(df.Timestamp, errors='coerce')

In [164]: df
Out[164]:
                   Timestamp        Clientip
0 2015-07-22 02:40:06.499174  106.51.235.133
1 2015-07-22 02:50:06.000000  106.51.235.133
2 2015-07-22 02:40:06.632589  115.250.16.146
3 2015-07-22 03:30:16.111111  115.250.16.146

In [165]: df.groupby('Clientip')['Timestamp'].apply(lambda s: (s - s.shift(1) > pd.Timedelta("15 min")).fillna(0).cumsum(skipna=False))
Out[165]:
0    0
1    0
2    0
3    1
Name: Timestamp, dtype: int32

时间戳是ISO 8601格式的字符串,精度为微秒(应该用datetime.isoformat生成)。它们也是unicode格式(python3调用这些字符串),但只包含ASCII。使用适当的格式字符串,您可以用datetime.strptime解析它们。在Pandas中,适当的函数称为to_datetime。在

相关问题 更多 >

    热门问题