【问题标题】:Invalid syntax in SpyderSpyder 中的无效语法
【发布时间】:2021-06-19 08:53:55
【问题描述】:

我正在尝试根据名称中的某些字符串(例如“日期”)制作列名列表。

date_cols = [col in df.columns if 'date' in col]

为什么这个命令在 spyder 上给了我无效的语法?

【问题讨论】:

    标签: python pandas spyder


    【解决方案1】:

    你需要的是:

    date_cols = [col for col in df.columns if 'date' in col]
    

    语法是:

    [*expression* for *target* in *iterable* if *conditional*]
    

    其中 expression 是可以使用一个或多个目标名称或任何其他值的任何有效表达式; target 是一个或多个以列分隔的名称; iterable 是任何可迭代的,包括 list/set/dictionary/dataframe 和许多其他; conditional 是基于一个或多个目标名称的 True/False 表达式

    【讨论】:

      【解决方案2】:

      您可以使用for..in 循环,条件如下。

      date_cols = [col for col in df.columns if 'date' in col]
      

      【讨论】:

        猜你喜欢
        • 2021-11-20
        • 2017-11-14
        • 2020-03-29
        • 1970-01-01
        • 2018-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多