python - 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 中。我有更好的方法来实现目标吗?
解决方案
既然你问过另一种方法。与其在 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)
推荐阅读
- reactjs - Gatsby 使用 slug 查询特定帖子
- rust - 如何读取类函数宏的输入参数的值?
- java - 从 android 服务调用 Dart 函数
- bash - 应脚本:合并文件,如何在awk输出的每一行开头添加一些字符
- gradle - 迁移到 Java 11 后 Gradle 构建时间变慢
- powershell - 如何列出给定文件夹输入的第一级子文件夹的 ACL
- ios - 动态产品列表的应用内购买
- amazon-web-services - InvalidParameterCombination:数据库实例和 EC2 安全组在不同的 VPC 中
- python - 为什么 Python 在不满足所有条件的情况下退出 while 循环?
- vb.net - 按 X 和 Y 属性排序列表