使用astype将dtype转换为str,然后使用vectorised str方法对str进行切片,然后再次转换回int64 dtype:
In [184]:
df['DATE'] = df['DATE'].astype(str).str[:-2].astype(np.int64)
df
Out[184]:
DATE
0 201107
1 201107
2 201107
3 201107
4 201107
5 201107
6 201107
7 201108
8 201108
9 201108
In [185]:
df.info()
Int64Index: 10 entries, 0 to 9
Data columns (total 1 columns):
DATE 10 non-null int64
dtypes: int64(1)
memory usage: 160.0 bytes
嗯…
原来有一个内置的方法floordiv:
In [191]:
df['DATE'].floordiv(100)
Out[191]:
0 201107
1 201107
2 201107
3 201107
4 201107
5 201107
6 201107
7 201108
8 201108
9 201108
Name: DATE, dtype: int64
更新
对于1000行df,floordiv方法要快得多:
%timeit df['DATE'].astype(str).str[:-2].astype(np.int64)
%timeit df['DATE'].floordiv(100)
100 loops, best of 3: 2.92 ms per loop
1000 loops, best of 3: 203 ?s per loop
在这里我们观察到~10倍的加速