【问题标题】:List Comprehension - Select Columns based on a Variable列表理解 - 根据变量选择列
【发布时间】:2015-12-18 10:36:04
【问题描述】:

我的数据框是 ELA 和数学列的汇编。当我允许用户输入选择一个主题时,我最终想删除其中一个主题的列。

我正在尝试使用列表推导来为数据框分配具有选定主题名称的任何列。一个细微差别是,在 ELA 和数学选择中,有两列应该保持不变,即“熟练类别数学”和“熟练类别 ELA”。

关于如何使用列表推导来完成此任务的想法?

输入:

    ELA Score  Math Score  ELA Goal   Math Goal   Proficiency ELA  Proficiency Math
        1          4          6           7              3                 5

输出:(with subject_selection = 'Math')

    Math Score   Math Goal   Proficiency ELA   Proficiency Math
        4            7             3                   5

我当前的代码:

    col_list = df.columns
    subject_selection = 'Math'   ###User types in desired subject
    x = df['Proficiency Category Math']
    y = df['Proficiency Category ELA']
    df = [cols for cols in col_list if subject_selection in cols or cols == x or cols == y]

我收到的错误是:

    TypeError: invalid type comparison

【问题讨论】:

  • 您将列名与行中的值(int)进行比较。
  • 如果您打印col_list,它会是什么样子? (任何条目中是否包含字符串“数学”?)
  • @jcfollower col_list 应该是我的数据框中的列名列表。我想知道我的问题是否是我正在使用列表理解来过滤掉系列对象?
  • 只要col_list 看起来像这样,您的列表理解就可以了...["ELA Score", "Math Score", "ELA Goal", "Math Goal", "Proficiency ELA", "Proficiency Math"]

标签: python string filter dataframe list-comprehension


【解决方案1】:

您需要将列的 name 与要包含的列的 name 进行比较,就像对 subject_selection 所做的那样。换句话说,你做了subject_selection = 'Math',而不是subject_selection = df[['Math Score', 'Math Goal']]。同样,您应该这样做:

x = 'Proficiency Category Math'
y = 'Proficiency Category ELA'

【讨论】:

  • 好的!我意识到了这个重大问题。在我修复它之后,我没有得到我想要的结果。我得到一个只包含我的 x 和 y 变量的列表。我的列表理解有问题吗?@BrenBarn
  • @krisko08:您需要提供一个独立的、可重现的示例来说明问题。
猜你喜欢
  • 1970-01-01
  • 2022-12-22
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 2019-10-11
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多