将一列时间戳转换为以 pandas 为单位的句点 [英] Convert a column of timestamps into periods in pandas

查看:123
本文介绍了将一列时间戳转换为以 pandas 为单位的句点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列时间戳,需要将其转换为句点(月").例如

I have a column of timestamps that need to be converted into period ('Month'). e.g.

1985-12-31 00:00:00 to 1985-12

熊猫具有.to_period函数,但仅适用于时间戳索引,不适用于列.因此,您只能有一个期间索引,而不能有一个期间列?

Pandas have a .to_period function, but it only works for timestamps index, not column. So you can only have a period index, but not a period column?

并且仅在时间戳是唯一索引的情况下才有效.也就是说,如果时间戳记是multIndex的一部分,则.to_period()函数也不起作用.

And it only work if timestamps is the only index. That is, if timestamps are part of a multIndex, the .to_period() function doesn't work as well.

熊猫似乎认为人们将始终使用时间戳和句点作为索引,而不是单个列,显然不是这种情况.

It seems that Pandas assume people will always use timestamps and periods as index, but not a single column, which is apparently not the case.

无论如何我都能解决吗?或者,如果不在Pandas中,可以用numpy完成吗?

Anyway I can get around with this? Or if not in Pandas, can it be done in numpy?

谢谢!

推荐答案

我今天碰到了这个线程,在进一步挖掘发现Pandas .15提供了使用.dt的更简单选项之后,您可以避免创建索引的步骤并直接创建该列.您可以使用以下命令获得相同的结果:

I came across this thread today, and after further digging found that Pandas .15 affords an easier option use .dt, you can avoid the step of creating an index and create the column directly. You can use the following to get the same result:

df[1] = df[0].dt.to_period('M')

这篇关于将一列时间戳转换为以 pandas 为单位的句点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆