检查数据帧是否是布尔型pandas

cur*_*gie 8 python dataframe pandas

我有一个pandas DataFrame如下:

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
Run Code Online (Sandbox Code Playgroud)

我需要检查dtype这个数据帧是否是bool.我尝试过:

In [109]: print isinstance(df1, bool)
False
Run Code Online (Sandbox Code Playgroud)

**它应该返回**True****

我怎样才能做到这一点?

参考:检查变量是否为数据帧

EdC*_*ica 7

您可以打印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')
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下df1.v.dtypes应该打印与上面相同的输出

另外需要注意的是isinstance(df, bool),它不会起作用,因为它是一个熊猫数据帧或更准确:

In [7]:

type(df)
Out[7]:
pandas.core.frame.DataFrame
Run Code Online (Sandbox Code Playgroud)

需要注意的重要一点dtypes是,事实上numpy.dtype你可以这样做来比较类型的名称和字符串,但我认为isinstance在我看来更清楚,更可取:

In [13]:

df.a.dtypes.name == 'bool'
Out[13]:
True
Run Code Online (Sandbox Code Playgroud)

  • @curlyreggie `dytpes` 实际上是一个 `numpy.dtype` 参见:http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html,你也可以做 `df.a.dtypes .name == 'bool'` 会产生 `True` (2认同)