首页  >  文章  >  后端开发  >  如何提取数据框中部分字符串匹配的列?

如何提取数据框中部分字符串匹配的列?

Barbara Streisand
Barbara Streisand原创
2024-10-20 14:00:03838浏览

How to Extract Columns With Partial String Matches in a DataFrame?

查找部分字符串匹配的列

在 DataFrame 中查询包含特定字符串的列可能是一个有用的操作。但是,如果匹配不精确但包含某个子字符串怎么办?这就是正则表达式过滤器发挥作用的地方。

要查找名称包含特定字符串(特别是连续子字符串)的列,请考虑以下解决方案:

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

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

# Use regex filter to select columns with 'spike' substring
spike_cols = df.filter(regex='spike').columns.tolist()

# Print the column names with the matching substring
print(spike_cols)</code>

此代码迭代DataFrame 的列使用列表理解并应用正则表达式过滤器来查找具有“spike”子字符串的列。然后,生成的列名称列表将存储在Spike_cols变量中,该变量可用于根据需要访问相应的列。

另一种方法是将列名称转换为列表并迭代它们,测试每个列名称使用 for 循环和 if 语句匹配子字符串的名称:

<code class="python"># Column names converted to a list
col_list = list(df.columns)

# Iterate over the column names
for col in col_list:
    if 'spike' in col:
        # Column name with matching substring found
        print(col)</code>

通过使用这些方法,您可以有效地识别和访问 DataFrame 中名称包含特定字符串的列,即使它不是完全匹配。

以上是如何提取数据框中部分字符串匹配的列?的详细内容。更多信息请关注PHP中文网其他相关文章!

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