我有一个数据框,我有一个数字范围。我想找到特定列中的值位于该范围内的行。
这似乎是一项微不足道的工作。我尝试了这里给出的技术 - http://pandas.pydata.org/pandas-docs/dev/indexing.html#indexing-boolean
我举了一个简单的例子:
In [6]: df_s
Out[6]:
time value
0 1 3
1 2 4
2 3 3
3 4 4
4 5 3
5 6 2
6 7 2
7 8 3
8 9 3
In [7]: df_s[df_s.time.isin(range(1,8))]
Out[7]:
time value
0 1 3
1 2 4
2 3 3
3 4 4
4 5 3
5 6 2
6 7 2
然后,我尝试使用我正在使用的数据集中的一个样本,其中时间戳和值作为列:
In [8]: df_s = pd.DataFrame({'time': range(1379945743841,1379945743850), 'value': [3,4,3,4,3,2,2,3,3]})
In [9]: df_s
Out[9]:
time value
0 1379945743841 3
1 1379945743842 4
2 1379945743843 3
3 1379945743844 4
4 1379945743845 3
5 1379945743846 2
6 1379945743847 2
7 1379945743848 3
8 1379945743849 3
In [10]: df_s[df_s.time.isin(range(1379945743843,1379945743845))]
Out[10]:
Empty DataFrame
Columns: [time, value]
Index: []
为什么相同的技术在这种情况下不起作用?我究竟做错了什么?
我尝试了另一种方法:
In [11]: df_s[df_s.time >= 1379945743843 and df_s.time <=1379945743845]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-11-45c44def41b4> in <module>()
----> 1 df_s[df_s.time >= 1379945743843 and df_s.time <=1379945743845]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
然后,我尝试了一种更复杂的方法:
In [13]: df_s.ix[[idx for idx in df_s.index if df_s.ix[idx]['time'] in range(1379945743843, 1379945743845)]]
Out[13]:
time value
2 1379945743843 3
3 1379945743844 4
这给出了预期的结果,但是在我的原始数据集上给出任何结果需要太多时间。它有 209920 行,当我实际测试我的代码时,预计行数会增加。
任何人都可以指导我采取正确的方法吗?
我正在使用 python 2.7.3 和 pandas 0.12.0
更新:
杰夫的回答奏效了。
但我发现这种isin
方法更简单、直观且不那么混乱。如果有人知道它失败的原因,请发表评论。
谢谢!