我有以下数据框:
DateTime Seq
timestamp
1475504294990,10/03/2016 10:18:14:990000,2123847
1475504446660,10/03/2016 10:20:46:660000,2123908
1475504524410,10/03/2016 10:22:04:410000,2123953
1475504848100,10/03/2016 10:27:28:100000,2124067
1475504940530,10/03/2016 10:29:00:530000,2124126
我想使用开始和结束时间戳对这个数据帧进行切片
start = 1475504446660
end = 1475504848100
print df[start:end]
DateTime Seq
timestamp
1475504446660,10/03/2016 10:20:46:660000,2123908
1475504524410,10/03/2016 10:22:04:410000,2123953
1475504848100,10/03/2016 10:27:28:100000,2124067
但是,我收到此错误:
IndexError: failed to coerce slice entry of type long to integer
我尝试使用 df[int(start):int(end)],仍然得到同样的错误
最佳答案
要切片,您必须将时间戳定义为索引并使用 loc
执行标签索引(否则整数索引的位置和标签索引之间存在歧义)。
df = df.set_index('timestamp')
df.loc[start:end]
# DateTime Seq
# timestamp
# 1475504446660 10/03/2016 10:20:46:660000 2123908
# 1475504524410 10/03/2016 10:22:04:410000 2123953
# 1475504848100 10/03/2016 10:27:28:100000 2124067
默认情况下,在
integer
索引的情况下,索引是按位置而不是标签进行的,请参见本示例中的结果。df[0:2] # equivalent to df.iloc[0:2]
# DateTime Seq
# timestamp
# 1475504294990 10/03/2016 10:18:14:990000 2123847
# 1475504446660 10/03/2016 10:20:46:660000 2123908
笔记
如果您不想将
timestamp
定义为索引,您可以使用此语法来获得相同的结果。df.query('@start <= timestamp <= @end')
# timestamp DateTime Seq
# 1 1475504446660 10/03/2016 10:20:46:660000 2123908
# 2 1475504524410 10/03/2016 10:22:04:410000 2123953
# 3 1475504848100 10/03/2016 10:27:28:100000 2124067
关于Python Pandas : How to slice dataframe using 13 digit timestamp,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41247967/