根据条件在熊猫数据框中选择行不起作用

时间:2021-04-30 15:27:51

标签: python pandas

我有一个带有“时间戳”列的数据框,如下所示:

df[Timestamp]

0            1.341709
1            1.343688
2            1.344503
3            1.344593
4            1.344700
              ...    
1263453    413.056745
1263454    413.056836
1263455    413.056945
1263456    413.057046
1263457    413.057153
Name: Timestamp, Length: 1263458, dtype: float64

现在我有两个变量来定义区间的开始和结束,如下所示:

start = 10
end = 15

要选择时间戳位于“开始”和“结束”之间的数据帧中的所有行,我使用查询方法:

df_want = df.query("@start <= Timestamp < @end")

虽然这给了我一个类型错误

TypeError: '<=' not supported between instances of 'int' and 'type'

为什么这不起作用,时间戳不应该是'float64'类型吗?为什么只是“类型”?

2 个答案:

答案 0 :(得分:2)

您需要执行以下操作:

df_want = df[df['Timestamp'].between(start,end)]

答案 1 :(得分:0)

与变量

df[(df['Timestamp'] >= start) & (df['Timestamp'] <= end)]

使用硬编码的值:

df[(df['Timestamp'] >= 15) & (df['Timestamp'] <= 30)]
相关问题