用于标记数据的Numpy逻辑条件

问题描述 投票:0回答:1

我正在尝试创建另一个标签列,该列基于我现有数据中的多个条件

df

ind group people value value_50 val_minmax
 1     1    5    100    1        10
 1     2    2    90     1        na
 2     1    10   80     1        80
 2     2    20   40     0        na
 3     1    7    10     0        10
 3     2    23   30     0        na

import pandas as pd 
import numpy as np 

df = pd.read_clipboard()

然后尝试按照以下条件将标签放在行上

df['label'] = np.where(np.logical_and(df.group == 2, df.value_50 == 1, df.value > 50), 1, 0)

但它给了我一个错误

TypeError: return arrays must be of ArrayType

如何在python中执行它?

python pandas numpy dataframe where
1个回答
2
投票

在面具之间使用&

df['label'] = np.where((df.group == 2) & (df.value_50 == 1) & (df.value > 50), 1, 0)

替代方案:

df['label'] = ((df.group == 2) & (df.value_50 == 1) & (df.value > 50)).astype(int)

如果将reduce与布尔掩码列表一起使用,您的解决方案应该有效:

mask = np.logical_and.reduce([df.group == 2, df.value_50 == 1, df.value > 50])
df['label'] = np.where(mask, 1, 0)
#alternative
#df['label'] = mask.astype(int)
© www.soinside.com 2019 - 2024. All rights reserved.