python - Pandas:如何获取日期列的年月?

标签 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')

但是需要很长时间

最佳答案

您的解决方案比较大的 DataFrame 中的 strftime 更快,但有不同的输出 - Periods 与 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)

关于python - Pandas:如何获取日期列的年月?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52311836/

相关文章:

python - 使用 aggfunc 时出现 pandas InvalidIndexError

c - 在 C 中打印时间 (0) 的格式说明符

go - 无法使用 if val 从 Golang 中的 map[time.Time]Measure 获取值,ok := mapMeasures[ts]; ok {}

python - 抓取的网络数据中缺少信息,谷歌翻译,使用Python

Python 嵌入 : PyImport_Import not from the current directory

python - Panda 0.22 dataframe.drop 比它应该多的行

python - 检查列值是否大于 pandas 列和 python 变量之间的最大值

python - 如果我有解释器,为什么还要使用 Parrot(或其他虚拟机)?

python - 如何获取列中最频繁值的数量?

php - SQL/PHP : get all results within time X to Y, 检测中间是否有可用时间