Skip to main content
 首页 » 编程设计

python之加速 Pandas : find all columns which fullfill set of conditions

2025年05月04日13dyllove98

我有使用 pandas DataFrame 表示的数据,例如如下所示:

| id | entity | name | value | location 

其中 id 是一个 integer 值,entity 是一个 integer ,name 是一个 string,value 是一个 integer,location 是一个 string (例如美国、加拿大、英国等)。

现在,我想向这个数据框添加一个新列,列“flag”,其中的值分配如下:

for d in df.iterrows(): 
 
    if d.entity == 10 and d.value != 1000 and d.location == CA: 
        d.flag = "A"  
    elif d.entity != 10 and d.entity != 0 and d.value == 1000 and d.location == US: 
        d.flag = "C" 
    elif d.entity == 0 and d.value == 1000 and d.location == US" 
        d.flag = "B" 
    else: 
        print("Different case") 

有没有办法加快速度并使用一些内置函数而不是 for 循环?

请您参考如下方法:

使用np.select你传递一个条件列表,根据这些条件你给它选择,当没有满足任何条件时你可以指定一个默认值。

conditions = [ 
    (d.entity == 10) & (d.value != 1000) & (d.location == 'CA'), 
    (d.entity != 10) & (d.entity != 0) & (d.value == 1000) & (d.location == 'US'), 
    (d.entity == 0) & (d.value == 1000) & (d.location == 'US') 
] 
 
choices = ["A", "C", "B"] 
 
df['flag'] = np.select(conditions, choices, default="Different case")