pandas 检查数据框是否为布尔类型熊猫
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21982681/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if dataframe is of boolean type pandas
提问by curlyreggie
I have a pandas DataFrame as below:
我有一个Pandas数据框如下:
In [108]: df1
Out[108]: 
                         v
t                         
2014-02-21 10:30:43  False
2014-02-21 10:31:34  False
2014-02-21 10:32:25  False
2014-02-21 10:33:17  False
2014-02-21 10:34:09  False
2014-02-21 10:35:00  False
2014-02-21 10:35:51  False
I need to check if the dtypeof this dataframe is bool. I tried with:
我需要检查dtype这个数据框的bool. 我试过:
In [109]: print isinstance(df1, bool)
False
**It should return **True****
**它应该返回 **True****
How can I do this?
我怎样才能做到这一点?
Reference: check if variable is dataframe
参考:检查变量是否为数据框
采纳答案by EdChum
You can print the dtypesof the columns:
您可以打印dtypes列的:
In [2]:
import pandas as pd
df = pd.DataFrame({'a':[True,False,False]})
df
Out[2]:
       a
0   True
1  False
2  False
[3 rows x 1 columns]
In [3]:
df.dtypes
Out[3]:
a    bool
dtype: object
In [4]:
df.a.dtypes
Out[4]:
dtype('bool')
So in your case df1.v.dtypesshould print the same output as above
所以在你的情况下df1.v.dtypes应该打印与上面相同的输出
The other thing to note that isinstance(df, bool)will not work as it is a pandas dataframe or more accurately:
另一件需要注意的事情是,isinstance(df, bool)它是一个Pandas数据框或更准确地说是行不通的:
In [7]:
type(df)
Out[7]:
pandas.core.frame.DataFrame
The important thing to note is that dtypesis in fact a numpy.dtypeyou can do this to compare the name of the type with a string but I think isinstanceis clearer and preferable in my opinion:
需要注意的重要一点dtypes是,实际上numpy.dtype您可以这样做来将类型的名称与字符串进行比较,但我认为isinstance在我看来更清晰和更可取:
In [13]:
df.a.dtypes.name == 'bool'
Out[13]:
True

