我希望 pandas 数据框中的所有值都为 True/False,具体取决于值是否介于给定的 x 和 y 之间。
使用“AND”运算符或任何来自 pandas 的“介于”功能的 2 个数据帧的任何组合都很好。我不想遍历列并调用 pandas.Series.between(x, y) 函数。
示例
给定以下数据框
>>> df = pd.DataFrame([{1:1,2:2,3:6},{1:9,2:9,3:10}])
>>> df
1 2 3
0 1 2 6
1 9 9 10
我想要 x 和 y 之间的所有值。例如,我可以从:
>>> df > 2
1 2 3
0 False False True
1 True True True
然后做
>>> df < 10
1 2 3
0 True True True
1 True True False
然后
>>> df > 2 and df < 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Laurens Koppenol\Anaconda2\lib\site-packages\pandas\core\generic.py", line 731, in __nonzero__
.format(self.__class__.__name__))
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
最佳答案
将 &
与括号一起使用(由于运算符优先级),and
不理解如何处理 bool 值数组,因此出现警告:
In [64]:
df = pd.DataFrame([{1:1,2:2,3:6},{1:9,2:9,3:10}])
(df > 2) & (df < 10)
Out[64]:
1 2 3
0 False False True
1 True True False
可以使用 between
使用 apply
但这对于大 df 会更慢:
In [66]:
df.apply(lambda x: x.between(2,10, inclusive=False))
Out[66]:
1 2 3
0 False False True
1 True True False
请注意,每当您尝试使用 and
、or
和 not
比较 df 或系列时,都会发出此警告,您应该分别使用 &
、|
和 ~
,因为这些位运算符了解如何正确处理数组
关于python - 在数据框中查找值介于 x 和 y 之间的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766886/