【问题标题】:Python Join ListPython 加入列表
【发布时间】:2020-03-27 22:52:07
【问题描述】:

我最近在阅读有关 python 中的 VIF 函数实现的文章,我偶然发现了这篇文章。

Link to the article

我无法理解在这一特定行中发生的操作。

features = "+".join(df.columns - ["annual_inc"])

我明白当语句是

时的输出是什么
features = "+".join(df.columns)

谁能解释一下声明中- ["annual_inc"]的意义是什么?

【问题讨论】:

    标签: python python-3.x pandas list


    【解决方案1】:

    对于patsy.dmatrices,函数的第一个参数是formula_like,它必须是像y ~ x1 + x2 这样的字符串。在features 中,您正在创建一个包含所有列的字符串(在其间加入+),但目标变量annual_inc 除外。接下来,您必须将输入字符串创建为formula_like,即target ~ variable1 + variable2 + ...,在您的情况下为'annual_inc ~' + features

    dmatrices('annual_inc ~' + features, df, return_type='dataframe')
    

    参考patsy.dmatrices

    【讨论】:

      【解决方案2】:

      "annual_inc" 是回归的目标变量,因此被排除在特征集之外。

      【讨论】:

        【解决方案3】:

        我认为有使用旧的熊猫代码,现在引发错误:

        df = pd.DataFrame(columns=['a','b','annual_inc'])
        
        print (df.columns - ["annual_inc"])
        

        TypeError: 不支持的操作数类型 -: 'str' 和 'str'

        所以使用Index.difference 从列名中排除列表值:

        print(df.columns.difference(["annual_inc"]))
        Index(['a', 'b'], dtype='object')
        
        features = "+".join(df.columns.difference(["annual_inc"]))
        print(features)
        a+b
        

        【讨论】:

          猜你喜欢
          • 2015-10-07
          • 1970-01-01
          • 2013-01-26
          • 2018-03-15
          • 2015-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多