python - Pandas:应用函数:TypeError:不支持的操作数类型 -: 'unicode' 和 'unicode'

标签 python python-2.7 pandas

我有以下数据框df:

name    event_time
------------------------------------------
Mary   [(S, 2017-12-03T03:40:20.000Z), (V, 2017-12-07T02:51:32.000Z)]
Peter  [(S, 2017-11-02T01:11:10.000Z), (V, 2017-11-19T07:23:12.000Z)]
Andy   [(S, 2017-12-01T10:31:15.000Z), (V, 2017-12-09T12:31:10.000Z)]

然后,我使用以下代码来查找 event_time 字段中两个元素的持续时间:

df['duration'] = df.event_time.apply(lambda x:x[1][1]-x[0][1])

但是,我遇到了以下错误:

TypeError unsupported operand type(s) for -: 'unicode' and 'unicode' 
TypeErrorTraceback (most recent call last)
<ipython-input-7-7a191c6f2678> in <module>()
----> 1 df['duration'] = df.event_time.apply(lambda x:x[1][1]-x[0][1])

/opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
   2218         else:
   2219             values = self.asobject
-> 2220             mapped = lib.map_infer(values, f, convert=convert_dtype)
   2221 
   2222         if len(mapped) and isinstance(mapped[0], Series):

pandas/src/inference.pyx in pandas.lib.map_infer (pandas/lib.c:62658)()

<ipython-input-7-7a191c6f2678> in <lambda>(x)
----> 1 df['duration'] = df.event_time.apply(lambda x:x[1][1]-x[0][1])

TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode'

知道我在这里做错了什么吗?谢谢!

最佳答案

我相信您需要通过str[]选择值,转换to_datetime并减去:

s1 = pd.to_datetime(df['event_time'].str[1].str[1])
s2 = pd.to_datetime(df['event_time'].str[0].str[1])
df['duration'] =  s1 - s2
print (df)
    name                                         event_time         duration
0   Mary  [(S, 2017-12-03T03:40:20.000Z), (V, 2017-12-07...  3 days 23:11:12
1  Peter  [(S, 2017-11-02T01:11:10.000Z), (V, 2017-11-19... 17 days 06:12:02
2   Andy  [(S, 2017-12-01T10:31:15.000Z), (V, 2017-12-09...  8 days 01:59:55

关于python - Pandas:应用函数:TypeError:不支持的操作数类型 -: 'unicode' 和 'unicode',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47747703/

相关文章:

python - 为什么将 %r 与元组一起使用时会得到 "Not all arguments converted"?

python-2.7 - Debian 中的 SSL 证书未更新

python - 如何在python中列出目录中的文件?

python - 在同一个图上使用 Matplotlib 和 Pandas 绘制图

python - CPLEX 二次 objective-c PLEX 错误 1017 : Not available for mixed-integer problems

python - 将 Bigquery 结果转换为 Pandas Data Frame

python - Pandas 在中间行上移动列中的值

python - 如何在 df.iterrows() 期间删除 Pandas 数据框中的当前行

python - 我可以在我用 html 和 css 中的 svg 制作的笔触动画上使线条更粗吗?

python - 在 PyCharm 中的远程解释器上运行远程脚本