我有一个数据帧,持续时间是其中一个属性。持续时间的内容如下:

            array(['487', '346', ...,  '227', '17']).

以及df.info(),我得到:数据列(总共22列):
             duration        2999 non-null object
             campaign        2999 non-null object
             ...

现在我想把持续时间转换成整数。有什么解决办法吗?

最佳答案

使用astype

df['duration'] = df['duration'].astype(int)

时间安排
使用以下设置生成大型示例数据集:
n = 10**5
data = list(map(str, np.random.randint(10**4, size=n)))
df = pd.DataFrame({'duration': data})

我有以下时间安排:
%timeit -n 100 df['duration'].astype(int)
100 loops, best of 3: 10.9 ms per loop

%timeit -n 100 df['duration'].apply(int)
100 loops, best of 3: 44.3 ms per loop

%timeit -n 100 df['duration'].apply(lambda x: int(x))
100 loops, best of 3: 60.1 ms per loop

09-11 19:00
查看更多