Python 熊猫:如何计算日期列的年-月?
我有一个很大的数据框Python 熊猫:如何计算日期列的年-月?,python,pandas,time,Python,Pandas,Time,我有一个很大的数据框df,它以%Y-%m-%d的形式包含日期 df val date 0 356 2017-01-03 1 27 2017-03-28 2 33 2017-07-12 3 455 2017-09-14 我想创建一个新列YearMonth,其中包含格式为%Y%m df['YearMonth'] = df['date'].dt.to_period('M') 但是它需要很长的时间在较大的数据帧中,您的解决方案比strftime更快
df
,它以%Y-%m-%d
的形式包含日期
df
val date
0 356 2017-01-03
1 27 2017-03-28
2 33 2017-07-12
3 455 2017-09-14
我想创建一个新列YearMonth
,其中包含格式为%Y%m
df['YearMonth'] = df['date'].dt.to_period('M')
但是它需要很长的时间在较大的
数据帧
中,您的解决方案比strftime
更快,但输出时间不同-周期
与字符串
:
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'>
列表理解也很慢:
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)
如果
date
列尚未转换为字符串,则可以将其转换为字符串,然后截断为年份和月份(即前七个字符)
稍微长一点,但不太明显。你的解决方案更直观,也是我会选择的,你比我快。你是如何在[66]%timeit中复制笔记本的,包括单元格编号和输出的
。
@pyd-使用复制(原始文本)什么快捷键?@pyd-Ctrl+Shift+C
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)
df['YearMonth'] = df['date'].astype(str).str[:7]
val date YearMonth
0 356 2017-01-03 2017-01
1 27 2017-03-28 2017-03
2 33 2017-07-12 2017-07
3 455 2017-09-14 2017-09