首页  >  文章  >  后端开发  >  如何使用正则表达式迭代提取 pandas DataFrame 中匹配子字符串的列?

如何使用正则表达式迭代提取 pandas DataFrame 中匹配子字符串的列?

Susan Sarandon
Susan Sarandon原创
2024-10-20 13:58:29496浏览

How to Extract Columns with Matching Substrings in pandas DataFrame Iteratively and Using Regular Expressions?

识别包含特定子字符串的列

要定位名称包含指定子字符串而不需要精确匹配的列,可以采用迭代方法。这涉及检查每个列名称并识别那些满足搜索条件的列名称。

考虑一个具有列名称(例如“spike-2”、“hey spike”和“spiked-in”)的 DataFrame。要提取包含子字符串“spike”的列名称,可以使用以下Python代码:

<code class="python">import pandas as pd

# Initialize data
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)

# Iterate over column names and filter based on substring
spike_cols = [col for col in df.columns if 'spike' in col]

# Print resulting column names
print(spike_cols)</code>

在此代码中:

  1. df.columns 返回列的列表
  2. 列表理解 [col for col in df.columns if 'spike' in col] 使用变量 col 迭代每个列名称,并构造一个仅包含包含子字符串 'spike' 的名称的新列表.
  3. 生成的 spike_cols 包含所需的列名称,稍后可以使用 df['col_name'] 或 df[col_name] 访问。

或者,通过以下方式获取 DataFrame仅匹配列:

<code class="python">df2 = df.filter(regex='spike')</code>

这将创建仅包含名称包含“spike”的列的 df2。

以上是如何使用正则表达式迭代提取 pandas DataFrame 中匹配子字符串的列?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn