【问题标题】:SAS Data Step Vs PandasSAS 数据步与熊猫
【发布时间】:2020-05-10 03:35:58
【问题描述】:

我需要在 python 中创建一个决策树(编码)。在 sas 中会是这样的

假设一个名为 original 的数据集包含三列 c1、c2、c3

data temp;
set original;
if c1 > 10 and c2 < 6 then res = c1*c2;
else 
  if c3 < 27 or c2 > 9 then res = 6.3;
  else if c1 > 57 or c3 > 38 then res = 10;
    else res = 0;
run;

这将创建一个名为 temp 的数据集,其中包含与原始列相同的列以及一个列“res”,其中表的每一行具有适当的值(取决于每一行的 c1、c2、c3 的值)

我在 python 中尝试过这样的事情:

temp = original
if ((temp['c1'] > 10) & (temp['c2'] < 6)):
  temp['res'] = temp['c1']*temp['c2']
else:  
  if ((temp['c3'] < 27) | (temp['c2'] > 9)):
    temp['res'] = 6.3
  else:
    if ((temp['c1'] > 57) | (temp['c3'] > 38)):
      temp['res']= 10;
    else:
      temp['res']= 0;

第一次比较时它一直告诉我语法错误 if ((temp['c1'] > 10) & (temp['c2']

如何在列级别进行数据比较,但要基于常数(或另一列)的特定比较

在 sas 中我不需要索引行和列(就像我在 C 中所做的那样)只需要引用列并且执行是逐行的

任何帮助都非常感谢它

马丁

【问题讨论】:

  • 你也可以在python中使用andor
  • Python 和 SAS 是完全不同的语言。最好将您对 SAS 的了解完全抛在脑后,按照自己的方式学习 Python。注意,temp = original 不会创建副本,它只是将同一个对象分配给另一个名称
  • 反正语法错误是由于&amp;&amp;,它不是Python中的运算符。您的意思可能是 &amp;elementwise 比较,假设您正在使用 pandas 对象...但请注意,由于 &amp; 的优先级,您可能希望使用括号。
  • 谢谢Juanpa,是的,pandas,我的意思是'&'。我也试过'and',错误在于比较。我知道 sas 和 python 是不同的,两者都很好。但我需要表示一个用 python 编码的决策树。
  • 上述没有给出语法错误

标签: python pandas sas


【解决方案1】:

考虑numpy.where 用于数组的条件分配。由于使用了嵌套if/else,所以运行嵌套条件:

temp['res'] = np.where((temp['c1'] > 10) & (temp['c2'] < 6),
                       temp['c1'] * temp['c2'],
                       np.where((temp['c3'] < 27) | (temp['c2'] > 9),
                                6.3,
                                np.where((temp['c1'] > 57) | (temp['c3'] > 38),
                                         10, 0)
                       )
              )

或者,numpy.select:

cond_list = [(temp['c1'] > 10) & (temp['c2'] < 6),
             (temp['c3'] < 27) | (temp['c2'] > 9),
             (temp['c1'] > 57) | (temp['c3'] > 38)]

value_list = [temp['c1'] * temp['c2'], 6.3, 10]


temp['res'] = np.select(cond_list, value_list, default=0)

【讨论】:

  • 冻糕,非常感谢!..你知道在嵌套 np.where's 方面是否有任何限制吗? (它似乎是最接近 if-else as sas 的。
  • 我不知道有什么限制。但是,通常在编程中运行太多逻辑 if 条件表明 代码异味,您可以使用合并和子集进行重构。
猜你喜欢
  • 1970-01-01
  • 2020-05-17
  • 2021-06-27
  • 2020-06-03
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
相关资源
最近更新 更多