将多条件掩码应用于数据框

Apply multi conditional mask to dataframe

我需要对我的稀疏矩阵应用掩码 df,然后将布尔值转换为 1.0,如下所示:

link = 16.0 
mask = (df<=link) 
# convert lesser values to 1
df = df.where(mask, 1.0)

这行得通。但是现在我需要使用另一个条件来屏蔽,像这样:

mask = (df<=link) & (df!=0.0)

或:

mask = ((df<=link) & (df!=0.0))

但这会引发错误:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

编辑:

df.dtypes 打印:

0       >f4
1       >f4
2       >f4
3       >f4
4       >f4
       ... 
1853    >f4
1854    >f4
1855    >f4
1856    >f4
1857    >f4
Length: 1858, dtype: object

这就是我得到矩阵的方式:

from astropy.io import fits

with fits.open('matrix_CEREBELLUM_large.fits') as data:
    df = pd.DataFrame(data[0].data)

link 到矩阵:

https://cosmosimfrazza.myfreesites.net/cosmic-web-and-brain-network-datasets


我错过了什么?

看线

brain_mask = (df<=brain_Llink & df<=brain_Llink!=0)

有两个细微的错误:df <= brain_Llink != 0,以及运算符优先级:a <= b & c != d 优先于 a <= (b & c) != d,但您想要 (a <= b) & (c != d)。所以修复:

brain_mask = ((df <= brain_Llink) & (df != 0))

#or

brain_mask = df.le(brain_Llink) & df.ne(0)

如果您收到关于

的错误
ValueError: Big-endian buffer not supported on little-endian compiler

这可能会导致您 然后这将解决它:

from astropy.io import fits

with fits.open('matrix_CEREBELLUM_large.fits') as data:
                                  # change from big-endian to little-endian
    df = pd.DataFrame(data[0].data.byteswap().newbyteorder())