初始化 Pandas 的全真布尔索引

And*_*rew 5 python pandas

我发现自己有时会迭代地构建布尔值/掩码,例如:

mask = initialize_mask_to_true()
for condition in conditions:
  mask = mask & condition

df_masked = pd.loc[mask, my_cols]
Run Code Online (Sandbox Code Playgroud)

其中条件可能是单独的布尔掩码或比较的列表,例如df[some_col] > someVal 是否有一个好的方法来执行initialize_mask_to_true()?有时我会做一些感觉丑陋的事情,例如:

mask = ~(df.loc[:, df.columns[0]] == np.nan)
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为它something == np.nan总是错误的,但感觉有一种更干净的方法。

kan*_*tal 10

如果必须保留索引:

mask= pd.DataFrame(True,index=df.index,columns=df.columns)
Run Code Online (Sandbox Code Playgroud)

或者

mask= pd.DataFrame(True,index=df.index,columns=[df.columns[0]])
Run Code Online (Sandbox Code Playgroud)

  • 好的。或者我认为,第二个例子更清晰:“mask = pd.Series(True, index=df.index)”? (12认同)

koP*_*tok 7

我使用numpy.ones来实现:

np.ones(df.shape[0], dtype=bool)
Run Code Online (Sandbox Code Playgroud)