如果列中的一行在不知道列名的情况下包含 "url" 或 "http",如何删除列?

How to drop columns if a row in a column has a "url"or "http" in it without knowing the column name?

如何删除 A 列,因为它在 python 中有以下“https://”?

背景故事:我有一个 500 列的数据框,其中 250 列是行中的“https://”链接,解释了先前的变量是什么。

目标是遍历 df 以删除具有“http://”的列

A B
https://mywebsite 25
https://mywebsite 42

我想要的输出是:

B
25
42

以下代码片段应该可以工作,删除 任何包含 url 的列

to_drop = []
for column in df:
  try:
      has_url = df[column].str.startswith('https://').any()
  except AttributeError:
      pass  # dtype is not string
  
  if has_url:
      to_drop.append(column)

df.drop(columns=to_drop, inplace=True)

对于每一列,它检查每一行是否以 'https://' 开头。如果其中任何一个这样做,那么它们将被添加到要删除的列的 'to_drop' 列表中。然后将此列表中的列删除。

如果 其中至少 50% 的值 是 URL,以下版本只会删除一列:

to_drop = []
for column in df:
  try:
      has_url = df[column].str.startswith('https://').mean() > 0.5
  except AttributeError:
      pass  # dtype is not string
  
  if has_url:
      to_drop.append(column)

df.drop(columns=to_drop, inplace=True)

你可以把0.5改成01之间的另一个数字来改变多大百分比的一部分应该是 URL,以便删除该列。