Python pandas:如何从数据帧的时间戳中获取小时?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24895913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python pandas: how to get hour from timestamp in dataframe?
提问by ilovedata17
I have a dataframe called DF that looks like this
我有一个名为 DF 的数据框,看起来像这样
time blah
2013-01-17 8:30 blah blah
2013-01-17 9:30 blah blah
The elements under time is of TimeStamp class. I want to grab all rows with hour == 8. How do I do it?
time 下的元素属于 TimeStamp 类。我想获取小时 == 8 的所有行。我该怎么做?
In R, it would be like this
在 R 中,它会是这样的
DF[DF$time$hour == 8,]
Thanks!
谢谢!
回答by abarnert
There are a few places you could be getting stuck here, and without code it's hard to know which one. So let's go through one by one.
有几个地方你可能会卡在这里,没有代码就很难知道是哪一个。那么让我们一一进行。
Note that most of this is explained in the documentation on TimeSeries(which also covers related classes like Timestamp, with relevant links where necessary), which will probably do a better job than I or anyone else on StackOverflow is likely to do…
请注意,大部分内容都在文档中进行了解释TimeSeries(其中还涵盖了相关类,例如Timestamp,在必要时提供相关链接),这可能比我或 StackOverflow 上的任何其他人做得更好......
Anyway, if you have a TimeSeries(or any series of Pandas objects), you can just access the members of the Timestamp(or other) objects through normal dot-attribute syntax and get back a new series or array, as appropriate. So, for example:
无论如何,如果您有一个TimeSeries(或任何系列的 Pandas 对象),您可以Timestamp通过正常的点属性语法访问(或其他)对象的成员,并根据需要返回一个新的系列或数组。因此,例如:
>>> df = pd.DataFrame({'blah': ('blah', 'blah')}, index=(pd.Timestamp('201301170830'), pd.Timestamp('201301070930'))
>>> ts = df.index
>>> ts.hour
array([8, 9])
So, if you want to get an array of booleans:
所以,如果你想获得一个布尔数组:
>>> df.index.hour == 8
array([True, False], dtype=bool)
Now, there are a zillion ways to select things in pandas (see the tutorial section on Selection), but one way to do it is:
现在,有无数种方法可以在 Pandas 中选择事物(请参阅有关Selection的教程部分),但一种方法是:
>>> df[df.index.hour == 8]
blah
2013-01-17 08:30:00 blah
Is that what you're looking for?
这就是你要找的吗?

