【问题标题】:Creating a Conditional Numerical List of Features in Python在 Python 中创建条件数字特征列表
【发布时间】:2019-11-22 11:20:55
【问题描述】:

鉴于功能列表中的任何字符串都包含在这些列的名称中,我正在尝试创建一个从列列表中提取的数字索引列表。

我尝试将列表推导与条件语句一起使用。但是,代码给了我一个类型错误“in requires string as left operand, not bool”。

import pandas as pd
feature_list = ['a', 'b']

x = pd.DataFrame({"data_a":[1,2,3], "data_b":[1,2,3], "data_c":[1,2,3]})

numerical_index_list = [x.columns.get_loc(a) for a in [b for b in list(x.columns) if any(c for c in feature_list) in b]]

谁能帮我获得一个条件列表理解,它会给我一个包含字符串 a 和 b ["data_a", "data_b"] 的列的列表?

【问题讨论】:

  • 问题代码在这里:if any(c for c in feature_list) in bany() 返回 TrueFalse,Python 抱怨它在 b 中找不到它
  • @darthbith 使用条件语句获得我想要的结果的正确方法是什么?

标签: python pandas list list-comprehension any


【解决方案1】:

您可以将feature_list 用作set 并查看它是否与列名相交。这似乎是您正在尝试的方法;尽管我认为这是错误的,因为 data 这个词中有一个,因此都通过了该测试。

features = set(feature_list)
cols = x.columns
[cols.get_loc(c) for c in cols if features.intersection(c)]
#[0, 1, 2]

也许使用更好的方法来确定列是否是feature_list 的子集?像if c[-1] in features 这样的东西?这样只有前 2 次通过,最后一次不会,因为 c 不在 feature_list 中。

[cols.get_loc(c) for c in cols if c[-1] in feature_list]
#[0, 1]

与您的评论更相关只需从列名中删除 "data_" 并使用第一种方法。

[cols.get_loc(c) for c in cols if features.intersection('_'.join(c.split('_')[1:]))]
#[0, 1]

【讨论】:

  • 最后一段代码的问题在于实际的列包含的不仅仅是一个字母。例如 data_revenuestream 或 data_cash。
  • 只需使用'_'.join(c.split('_')[1:]) 完全删除data_
  • 编辑了我的答案以包含该内容
  • 那只是给了我一个空列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 2022-10-23
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多