[英]How to check in pandas that column is bool-like (includes either True, False or NaN)?
我有一個 dataframe 像這樣:
df = pd.DataFrame(
{
'date':"20220701",
'a':[1,2,np.NaN],
'b':['a', 'b', 'c'],
'c':[True, False, np.NaN]
}
)
因此, b
列和c
的數據類型為 object。我希望能夠有效地區分列,如果它們沒有缺失值,則可能是 boolean。
我想到的唯一解決方案是:
檢查列中的唯一值是否在 [true, false, NaN] 中,但這很可能是非常低效的。
檢查哪里(df.c.isnull() | (df.c == True) | (df.c == False)).all()
這是使用分配的一種方法
由於該列是通過分配創建的,因此它是臨時的,而不是 df 的一部分。 所以,沒有丟失或添加任何東西
#create a temp column by ffill NA value, and check temp column dtype
df.assign(temp=df['c'].ffill())['temp'].dtype
dtype('bool')
>> df.assign(temp=df['c'].ffill())['temp'].dtype == 'bool'
True
或者
#list types of the column and the newly created one is of type bool
df.assign(temp=df['c'].ffill()).dtypes
date object
a float64
b object
c object
temp bool
dtype: object
您可以使用df.b[:10]
類的東西來代替使用unique()
並比較前 10 個樣本以假設您的數據是否為 boolean。
我認為它可能會失敗,但它會比unique()
更快......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.