【问题标题】:Select columns based on column name and location in Pandas根据 Pandas 中的列名和位置选择列
【发布时间】:2018-04-01 05:43:53
【问题描述】:

我有一个包含以下列的数据框,例如: 列名 = ID、姓名、dob、away_dur、away_count、in_dur、in_time 等。

我想根据以下条件选择数据并创建一个新的数据框: 1. 新的数据框应该包括第 4 到最后的列和 2. 新数据框不应该有以'in_'开头的列

我知道如何根据名称或位置提取列。但是我可以知道如何使用这两个条件来选择数据吗?

【问题讨论】:

    标签: python pandas select indexing


    【解决方案1】:

    你可以使用

    ndf = df.iloc[:,4:]
    ndf = ndf.iloc[:,~ndf.columns.str.startswith('in_')]
    

    【讨论】:

      【解决方案2】:

      使用 列表理解 过滤掉列。然后,使用df.tail

      c = [x for x in df.columns if not x.startswith('in_')]
      df = df[c].tail(-3)
      

      【讨论】:

        猜你喜欢
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-10
        • 1970-01-01
        • 2021-09-08
        • 1970-01-01
        • 2016-11-02
        相关资源
        最近更新 更多