使用正则表达式从数据框中提取特定的ID列

huangapple go评论63阅读模式
英文:

Using Regex to pull ID specific columns in a dataframe

问题

我有一个来自组织切片数据集的数据框,其中包含以下列

  • 图像
  • 名字
  • tumor_stroma_epi_nsclc_v2: 上皮 %
  • tumor_stroma_epi_nsclc_v2: 上皮面积(μm^2)
  • tumor_stroma_epi_nsclc_v2: 坏死 %
  • tumor_stroma_epi_nsclc_v2: 坏死面积(μm^2)
  • tumor_stroma_epi_nsclc_v2: 基质 %
  • tumor_stroma_epi_nsclc_v2: 基质面积(μm^2)
  • tumor_stroma_epi_nsclc_v2: 肿瘤 %
  • tumor_stroma_epi_nsclc_v2: 肿瘤面积(μm^2)
  • 面积(μm^2)

列名中的 nsclc_v2 部分根据不同的组织类型在多个不同数据集中是可变的。我想创建一个正则表达式,用于删除可以识别所有具有相同格式但不同组织类型的列的百分比列。到目前为止,以下是我能想到的内容。

tumor_temp.drop(columns=['Image', 'Name',
                        '^tumor_stroma_epi_[a-z0-9_]+: Epithelium %$',
                        '^tumor_stroma_epi_[a-z0-9_]+: Necrosis %$',
                        '^tumor_stroma_epi_[a-z0-9_]+: Stroma %$',
                        '^tumor_stroma_epi_[a-z0-9_]+: Tumor %$',
                        'Area μm^2'], inplace=True)

如果需要进一步的帮助,请告诉我。

英文:

I have a dataframe from a tissue slide dataset with the following columns

  • Image
  • Name
  • tumor_stroma_epi_nsclc_v2: Epithelium %
  • tumor_stroma_epi_nsclc_v2: Epithelium area µm^2
  • tumor_stroma_epi_nsclc_v2: Necrosis %
  • tumor_stroma_epi_nsclc_v2: Necrosis area µm^2
  • tumor_stroma_epi_nsclc_v2: Stroma %
  • tumor_stroma_epi_nsclc_v2: Stroma area µm^2
  • tumor_stroma_epi_nsclc_v2: Tumor %
  • tumor_stroma_epi_nsclc_v2: Tumor area µm^2
  • Area µm^2

The nsclc_v2 component of the columns is variable across multiple different datasets depending on the different tissue types. I want to create a regex to drop the % columns that can recognize all columns with the same format, but different tissue types. So far, this is all I was able to come up with.

tumor_temp.drop(columns=['Image','Name',
                         '^tumor_stroma_epi_[a-z0-9_]: Epithelium %$',
                         '^tumor_stroma_epi_[a-z0-9_]: Necrosis %$',
                         '^tumor_stroma_epi_[a-z0-9_]: Stroma %$',
                         '^tumor_stroma_epi_[a-z0-9_]: Tumor %$',
                         'Area µ?m^2'], inplace=True)

Apologies if this is a little basic, I mostly have an R background.

答案1

得分: 2

你可以使用pandas中的filter()函数:

import re

pattern = re.compile("^tumor_stroma_epi_[a-z0-9_]+:.*%$")  # 用于匹配包含%的列的正则表达式
cols_to_drop = df.filter(regex=pattern).columns
df.drop(columns=cols_to_drop, inplace=True)
英文:

You can use the filter() function from pandas:

import re

pattern = re.compile("^tumor_stroma_epi_[a-z0-9_]+:.*%$")  # regular expression to match columns with %
cols_to_drop = df.filter(regex=pattern).columns
df.drop(columns=cols_to_drop, inplace=True)

huangapple
  • 本文由 发表于 2023年4月7日 01:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定