我想用布尔值创建一个DataFrame,其中np.nan == False,任何正实数值== True。
import numpy as np
import pandas as pd
DF = pd.DataFrame({'a':[1,2,3,4,np.nan],'b':[np.nan,np.nan,np.nan,5,np.nan]})
DF.apply(bool) # Does not work
DF.where(DF.isnull() == False) # Does not work
DF[DF.isnull() == False] # Does not work
答案 0 :(得分:2)
很奇怪,但- np.isnan(df)
看起来比pd.notnull(df)
更能胜过山体滑坡:
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: df = pd.DataFrame({'a':[1,2,3,4,np.nan],'b':[np.nan,np.nan,np.nan,5,np.nan]})
In [4]: - np.isnan(df)
Out[4]:
a b
0 True False
1 True False
2 True False
3 True True
4 False False
In [5]: %timeit - np.isnan(df)
10000 loops, best of 3: 159 us per loop
In [6]: %timeit pd.notnull(df)
1000 loops, best of 3: 1.22 ms per loop
答案 1 :(得分:2)
In [11]: pd.notnull(df)
Out[11]:
a b
0 True False
1 True False
2 True False
3 True True
4 False False
答案 2 :(得分:0)
使用某些格式错误比较df上的notnull()和isnan():
df = pd.DataFrame({'a':[1,2,3,4,np.nan],'b':[np.nan,np.nan,np.nan,5,np.nan],'c':['fish','bear','cat','dog',np.nan]})
%%timeit
legit_dexes = np.isnan(df[df<=""].astype(float)) == False
1000次循环,每次循环最佳3:632 us
%%timeit
legit_dexes = pd.notnull(df)
1000循环,最佳3:每循环751 us
忽略格式错误列的这种变体也类似:
%%timeit
legit_dexes = np.isnan(df[df.columns[df.apply(lambda x: not np.any(x.values>=""))]]) == False
1000循环,每循环3:681 us