【问题标题】:Python Pandas: How to remove all columns from dataframe that contains the values in a list?Python Pandas:如何从包含列表中值的数据框中删除所有列?
【发布时间】:2018-06-17 19:46:37
【问题描述】:
include_cols_path = sys.argv[5]
with open(include_cols_path) as f:
include_cols = f.read().splitlines()

include_cols 是一个字符串列表

df1 = sqlContext.read.csv(input_path + '/' + lot_number +'.csv', header=True).toPandas()

df1 是一个大文件的数据框。我只想保留名称包含 include_cols 中任何字符串的列。

【问题讨论】:

标签: python pandas pyspark spark-dataframe


【解决方案1】:

pandas 中这样做肯定是个骗局。但是,您似乎正在将spark DataFrame 转换为pandas DataFrame

与其执行(昂贵的)收集操作并然后过滤您想要的列,不如在spark 一侧使用select() 进行过滤:

df1 = sqlContext.read.csv(input_path + '/' + lot_number +'.csv', header=True)
pandas_df = df1.select(include_cols).toPandas()

您还应该考虑转换为pandas DataFrame 是否真的是您想要做的。几乎所有你可以在pandas 做的事情也可以在spark 做。

编辑

我最初误解了你的问题。根据您的 cmets,我认为这就是您要寻找的:

selected_columns = [c for c in df1.columns if any([x in c for x in include_cols])]
pandas_df = df1.select(selected_columns).toPandas()

说明: 遍历df1 中的列,并仅保留列名中至少包含include_cols 中的一个字符串的那些。如果至少有一个条件是True,则any() 函数将返回True

【讨论】:

  • 非常感谢!如果我想搜索 df1 中的列包含来自 include_cols 的字符串 (%string%) 的位置,这是正确的语法吗?
  • 您的意思是过滤列列表以便只选择包含该字符串的列吗?如果是这样,试试这个:include_cols = [c for c in include_cols if 'string' in c](我假设你使用% 作为通配符。)如果你问如何过滤行,那是一个完全不同的问题。
  • 例如,如果 include_cols 包含 2 个值,'apple' 和 'orange',我想过滤 df1 中所有列名包含字符串,'apple' 和 'orange' 的列。我认为它应该接近这个但不确定:pandas_df = df1.select(col for col in df1.columns if include_cols in col]
  • 试试这个:pandas_df = df1.select([c for c in df1.columns if any([x in c for x in include_cols])])
【解决方案2】:
final_cols = [col for col in df.columns.values if col in include_cols]
df = df[final_cols]

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
【解决方案3】:
df1.loc[:, df1.columns.str.contains('|'.join(include_cols))]

例如:

df1 = pd.DataFrame(data=np.random.random((5, 5)), columns=list('ABCDE'))
include_cols = ['A', 'C', 'Z']
df1.loc[:, df1.columns.str.contains('|'.join(include_cols))]
>>>           A         C
    0  0.247271  0.761153
    1  0.390240  0.050055
    2  0.333401  0.823384
    3  0.821196  0.929520
    4  0.210226  0.406168

'|'.join(include_cols) 部分将使用输入列表的所有元素创建一个or 条件。在上面的例子中A|C|Z。如果使用列名上的.contains() 方法在列名中包含 元素之一,则此条件将为True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2018-08-18
    • 2018-01-21
    • 1970-01-01
    • 2023-01-28
    • 2013-01-17
    相关资源
    最近更新 更多