page contents

Pandas技巧:快速找到DataFrame中部分字符串匹配的行和列

在日常的数据处理中,经常需要在Pandas DataFrame中查找包含特定部分字符串的行和列。本文将详细介绍如何高效实现这一操作,提升你的数据处理效率。

attachments-2025-02-BzQ5HsWt67b3dfac26f89.png在日常的数据处理中,经常需要在Pandas DataFrame中查找包含特定部分字符串的行和列。本文将详细介绍如何高效实现这一操作,提升你的数据处理效率。

问题背景

假设你有一个包含大量数据的DataFrame,你需要找到包含某个特定子字符串的所有行和列。手动查找不仅费时费力,还容易出错。那么,如何利用Pandas实现这一功能呢?

解决方案

方法一:使用applycontains函数

 import pandas as pd

df = pd.DataFrame({'A': ['apple', 'banana', 'cherry'],
                   'B': ['dog', 'elephant', 'frog'],
                   'C': ['grape', 'honeydew', 'iguana']})

partial_string = 'ap'

## 找到包含部分字符串的列
matching_columns = df.apply(lambda x: x.astype(str).str.contains(partial_string, case=False).any())
matching_columns = matching_columns[matching_columns].index.tolist()

## 找到包含部分字符串的行
matching_rows = df.astype(str).apply(lambda x: x.str.contains(partial_string, case=False).any(), axis=1)
matching_rows = matching_rows[matching_rows].index.tolist()

print(f"包含'{partial_string}'的列: {matching_columns}")
print(f"包含'{partial_string}'的行: {matching_rows}")

方法二:使用stackunstack

 ## 找到包含部分字符串的单元格
matching_cells = df.stack().str.contains(partial_string, case=False).unstack()

## 找到包含部分字符串的列
matching_columns = matching_cells.any().index.tolist()

## 找到包含部分字符串的行
matching_rows = matching_cells.any(axis=1).index.tolist()

print(f"包含'{partial_string}'的列: {matching_columns}")
print(f"包含'{partial_string}'的行: {matching_rows}")

性能对比

两种方法各有优缺点,apply方法更直观,但性能稍差;stack方法性能较好,但代码稍显复杂。具体选择哪种方法,可根据实际数据量和需求决定。

总结

本文介绍了两种在Pandas DataFrame中查找包含部分字符串的行和列的方法,希望能帮助你在数据处理中更加高效。

更多相关技术内容咨询欢迎前往并持续关注好学星城论坛了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg

  • 发表于 2025-02-18 09:17
  • 阅读 ( 72 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
小柒
小柒

1980 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1980 文章
  3. Pack 1159 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章