我有一个熊猫数据框架,如下所示:
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
我需要检查这个数据帧的
dtype
是否是bool
。我尝试过:In [109]: print isinstance(df1, bool)
False
**应该返回**真**。*
我该怎么做?
参考:check if variable is dataframe
最佳答案
您可以打印列的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')
因此,在您的情况下,
df1.v.dtypes
应该打印与上面相同的输出另一件要注意的事情是,
isinstance(df, bool)
将不起作用,因为它是熊猫数据帧或更准确地说:In [7]:
type(df)
Out[7]:
pandas.core.frame.DataFrame
需要注意的一点是,
dtypes
实际上是anumpy.dtype
您可以这样做来将类型的名称与字符串进行比较,但我认为在我看来,isinstance
更清晰、更可取:In [13]:
df.a.dtypes.name == 'bool'
Out[13]:
True