Ваше решение быстрее, чем strftime
в большем DataFrame
, но есть другой вывод - Period
s против strings
:
df['YearMonth'] = df['date'].dt.strftime('%Y-%m')
df['YearMonth1'] = df['date'].dt.to_period('M')
print (type(df.loc[0, 'YearMonth']))
<class 'str'>
print (type(df.loc[0, 'YearMonth1']))
<class 'pandas._libs.tslibs.period.Period'>
#[40000 rows x 2 columns]
df = pd.concat([df] * 10000, ignore_index=True)
In [63]: %timeit df['date'].dt.strftime('%Y-%m')
237 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [64]: %timeit df['date'].dt.to_period('M')
57 ms ± 985 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Понимание спискаслишком медленно:
In [65]: %timeit df['new'] = [str(x)[:7] for x in df['date']]
209 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Другое решение Александра:
In [66]: %timeit df['date'].astype(str).str[:7]
236 ms ± 1.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)