基于多个条件创建列的干净方式

2024-04-25 16:49:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想创建一个名为“type”的新列。此列的值基于这些多个条件

  • 等级=7:QWE
  • 等级=8:ASD
  • 等级=1或2:ZXC
  • 等级=4、5或6,行业=170-490或570-690,职业=1000:IOP
  • 等级=4、5或6,行业=170-490或570-690,职业介于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  |
+----------+-------+------------+--------+------+

我的第一种方法基本上是使用dataframe查询方法创建每种类型的多个dataframe。但是,我发现了numpy“where”方法,目前我正在使用该方法的嵌套版本一步创建“type”列。然而,我觉得这是不可读的,我可以想象的情况下,有更多的条件,使这个过程看起来真的很混乱。有没有更干净的方法?也许用字典什么的?你知道吗


Tags: 方法dataframevaluetypejkl条件class行业
1条回答
网友
1楼 · 发布于 2024-04-25 16:49:34

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

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。请注意,您有重叠的条件,因此IOPJKL之间可能存在歧义

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

相关问题 更多 >