Skip to main content
 首页 » 编程设计

python之基于多个条件创建列的简洁方法

2025年05月04日23EasonJim

我的问题很简单 - 我有下表:

+----------+-------+------------+--------+ 
| industry | class | occupation | value  | 
+----------+-------+------------+--------+ 
|      170 |     4 |       1000 |  123.3 | 
|      180 |     7 |       3600 | 4543.8 | 
|      570 |     5 |        990 |  657.4 | 
+----------+-------+------------+--------+ 

我想创建一个名为“类型”的新列。该列的值是基于这多个条件

  • 7 级:QWE
  • 等级 = 8:自闭症
  • 类 = 1 或 2:ZXC
  • Class = 4、5 或 6 AND Industry = 170-490 或 570-690 AND Occupation >=1000:IOP
  • 类别 = 4、5 或 6 AND 行业 = 170-490 或 570-690 AND 职业在 10-3540 之间:JKL
  • 其他:BNM

结果表将如下所示:

+----------+-------+------------+--------+------+ 
| industry | class | occupation | value  | type | 
+----------+-------+------------+--------+------+ 
|      170 |     4 |       1000 |  123.3 | IOP  | 
|      180 |     7 |       3600 | 4543.8 | QWE  | 
|      570 |     5 |        990 |  657.4 | JKL  | 
+----------+-------+------------+--------+------+ 

我的第一个方法基本上是使用数据帧查询方法创建每种类型的多个数据帧。但是,我发现了 numpy 的“where”方法,我目前正在使用它的嵌套版本一步创建“type”列。但是,我觉得它不可读,我可以想象有更多条件会使这个过程看起来非常困惑的情况。有更清洁的方法吗?也许用字典什么的?

请您参考如下方法:

设置您的条件和输出并存储在列表中:

a = df['class'].eq(7)   
b = df['class'].eq(8)   
c = df['class'].isin([1,2])     
helper = df['class'].isin([4,5,6]) & (df.industry.isin(range(170, 491)) | df.industry.isin(range(570, 691))) 
d =  helper & df.occupation.ge(1000) 
e = helper & df.occupation.isin(range(10, 3541)) 
 
conds = [a, b, c, d, e] 
outs = ['QWE', 'ASD', 'ZXC', 'IOP', 'JKL'] 

使用 np.select。请注意,您有重叠条件,因此 IOP 和 JKL

之间可能存在歧义
df['out'] = np.select(conds, outs, default='BNM') 
 
   industry  class  occupation   value  out 
0       170      4        1000   123.3  IOP 
1       180      7        3600  4543.8  QWE 
2       570      5         990   657.4  JKL