Pandas 数据帧bool()
方法
原文:https://www.studytonight.com/pandas/pandas-dataframe-bool-method
在本教程中,我们将学习 PandasDataFrame.bool()
方法。它返回单个元素 DataFrame 的 bool。这必须是布尔标量值,True
或False
。如果数据帧没有恰好一个元素或者该元素不是布尔型的,它将引发ValueError
。
下图显示了DataFrame.bool()
方法的语法。
句法
使用此方法所需的语法如下。
DataFrame.bool()
示例 1:使用DataFrame.bool()
方法检查数据帧
仅当数据帧包含单个布尔真元素时,DataFrame.bool()
方法才返回True
。
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [True]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
一旦我们运行程序,我们将得到以下结果。
-数据帧- 列 0 真 数据帧是否包含单个布尔值:真
示例 2:使用DataFrame.bool()
方法检查数据帧
只有当数据帧包含单个 bool False 元素时,DataFrame.bool()
方法才返回False
。
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [False]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
一旦我们运行程序,我们将得到以下结果。
-数据帧- 列 0 假 数据帧是否包含单个布尔值:假
例 3:DataFrame.bool()
方法提升ValueError
如果数据帧包含两个元素,DataFrame.bool()
方法将引发ValueError
。
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [True,True]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
一旦我们运行程序,我们将得到以下结果。
-数据帧- 列 0 真 1 真 值错误:数据帧的真值不明确。请使用 a.empty、a.bool()、a.item()、a.any()或 a.all()。
示例:使用整数的DataFrame.bool()
方法的数据帧
如果数据帧包含整数元素,DataFrame.bool()
方法将引发ValueError
。
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [1]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
一旦我们运行程序,我们将得到以下结果。
-数据帧- 列 0 1 值错误:布尔不能作用于非布尔单元素数据帧
结论
在本教程中,我们学习了 PythonPandasDataFrame.bool()
方法。通过解决不同的例子,我们理解了这种方法是如何工作的。