首页 > 解决方案 > TypeError: must be str, not int 无法解决

问题描述

原来的时间数据是这样的:</p>

df['time'][0:4]

   2015-07-08
        05-11
        05-12
   2008-07-26

我希望所有这些数据都包含年份值。我应用了这个:

con_time = []

i=0
for i in df['time']:
    if len(df['time'])==5:
        time = '2018'+'-'+df['time']
        con_time.append(time)
        i +=1
    else:
        con_time.append(df['time']) 
        i +=1

发生了错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-78-b7d87c72f412> in <module>()
      8     else:
      9         con_time.append(df['time'])
---> 10         i +=1

TypeError: must be str, not int

这个错误太奇怪了....实际上我想创建一个新列表,将其转换为 np.array 并将其连接到 df 中。我有更好的方法来实现目标吗?

标签: pythonpandasnumpydataframe

解决方案


既然你问过另一种方法。与其在 python 中显式循环并填充列表,不如直接使用 DataFrame 方法。在你的情况下,这将是

df['time'].apply(lambda x: x if len(x) != 5 else '2018-'+x)

对于某些数据集,这可能运行得更快

编辑 我实际上使用随机玩具数据集运行了一个计时基准,其中包含约 50% 的完整和不完整日期。简而言之,对于小型数据集,简单的 for 循环解决方案似乎对于大型数据集更快,这两种方法都显示出相似的性能:

# 1M examples
import random
import numpy as np
y = pd.Series(np.random.randint(0,2,1000000))
s = {0:'2015-07-08',  1:'05-11'}
y = y.map(s)
%%timeit -n100
_ = y.apply(lambda x: x if len(x) != 5 else '2018-'+x)
>>> 275 ms ± 6.42 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit -n100
con_time = []
for i in y:
    if len(i)==5:
        time = '2018-'+i
        con_time.append(time)
    else:
        con_time.append(i) 
con_time_a = np.array(con_time)
>>> 289 ms ± 5.23 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

# 1K examples
import random
import numpy as np
y = pd.Series(np.random.randint(0,2,1000))
s = {0:'2015-07-08',  1:'05-11'}
y = y.map(s)
%%timeit -n100
_ = y.apply(lambda x: x if len(x) != 5 else '2018-'+x)
>>> 431 µs ± 70.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit -n100
con_time = []
for i in y:
    if len(i)==5:
        time = '2018-'+i
        con_time.append(time)
    else:
        con_time.append(i) 
con_time_a = np.array(con_time)
>>> 289 µs ± 40.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

推荐阅读