歡迎來到SO。該錯誤是由於pandas
框架下如何numpy
功能,考慮到這些例子:
In [158]:
a=np.array([1,2,1,1,1,1,2])
b=np.array([1,1,1,2,2,2,1])
In [159]:
#Array Boolean operation
a==1
Out[159]:
array([ True, False, True, True, True, True, False], dtype=bool)
In [160]:
#Array Boolean operation
b==1
Out[160]:
array([ True, True, True, False, False, False, True], dtype=bool)
In [161]:
#and is not an array Boolean operation
(a==1) and (b==1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-161-271ddf20f621> in <module>()
----> 1 (a==1) and (b==1)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [162]:
#But & operates on arrays
(a==1) & (b==1)
Out[162]:
array([ True, False, True, False, False, False, False], dtype=bool)
In [163]:
#Or *
(a==1) * (b==1)
Out[163]:
array([ True, False, True, False, False, False, False], dtype=bool)
In [164]:
df=pd.DataFrame({'a':a, 'b':b})
In [166]:
#Therefore this is a good approach
df[(df.a==1) & (df.b==1)]
Out[166]:
a b
0 1 1
2 1 1
2 rows × 2 columns
In [167]:
#This will also get you there, but it is not preferred.
df[df.a==1][df.b==1]
C:\Anaconda\lib\site-packages\pandas\core\frame.py:1686: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
"DataFrame index.", UserWarning)
Out[167]:
a b
0 1 1
2 1 1
2 rows × 2 columns
非常感謝朱CT,我看過你所有的代碼,它可以幫助我瞭解了很多:) @CT朱 –