python - Pandas:具有多个条件的 numpy.where 逻辑

标签 python pandas numpy

Python 数据科学新手

下面是我的Raw_data

raw_data = {'var1': ['true','false','ture'],'var2': [10,20,50], 'var3':['eggs','milk','eggs']}
df = pd.DataFrame(raw_data, columns = ['var1','var2','var3'])`

已测试代码但不起作用

def my_fun (var1,var2,var3,var4):
    df[var4]= np.where((df[var1] == 'true', 
                       df[var3] == 'eggs',
                       df[var2] < 10),
                       'hello',
                       'zello')
return df

这里我喜欢使用var1、var2和var3条件并获得条件结果。请帮忙

最佳答案

首先使用 bool 值 True/False 而不是字符串来简化逻辑。将此转换应用于系列'var1':

df['var1'] = df['var1'] == 'true'

然后您可以使用按位运算符&来比较 bool 系列:

def my_fun (var1,var2,var3,var4):
    df[var4]= np.where(df[var1] & df[var3].eq('eggs') & df[var2].lt(10),
                       'hello', 'zello')
    return df

效率较低的替代方案是使用np.ological_and.reduce:

def my_fun (var1,var2,var3,var4):
    conds = (df[var1], df[var3] == 'eggs', df[var2] < 10)
    df[var4]= np.where(np.logical_and.reduce(conds), 'hello', 'zello')
    return df

关于python - Pandas:具有多个条件的 numpy.where 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441359/

相关文章:

python - 元组解包顺序更改分配的值

python - 模块未找到错误 : No module named 'pyodbc' when importing pyodbc into py script

python - 如何将空列表添加到元组

python - 用 pandas 生成 "working hours"区间索引

python - 如何修复 numpy TypeError : unsupported operand type(s) for -: 'str' and 'str'

python - 在 NumPy 数组的可变位置插入新轴

python - 设置 matplotlib 极坐标图中中心标记的样式

python-3.x - 如何使用 dataframe.ewma 找到指数加权移动平均线?

python - 使用 pandas GroupBy.agg() 对同一列进行多次聚合

python - 在 Python 中获取用户输入范围