python - 如何根据列名称过滤数据框的内容

标签 python pandas

我想根据列名称过滤数据框(带有文本)。 对于给定的列,如果某个项目包含该列的名称,则保留该项目,如果不包含该项目,则将其删除。 给定行的内容是相同的。

考虑这个数据框:

dog                     cat                     monkey
The cat is beautiful    The cat is beautiful    The cat is beautiful
The dog is beautiful    The dog is beautiful    The dog is beautiful
The monkey is beautiful The monkey is beautiful The monkey is beautiful

以及预期:

dog                     cat                     monkey
The dog is beautiful    The cat is beautiful    The monkey is beautiful

谢谢你,

问候,

最佳答案

你可以试试这个:

df.where(df.apply(lambda x: x.str.contains(x.name))).bfill().head(1)

输出:

                    dog                   cat                   monkey
0  The dog is beautiful  The cat is beautiful  The monkey is beautiful

关于python - 如何根据列名称过滤数据框的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924970/

相关文章:

python - 为什么 python lambda 看到的是一个序列而不是一个值?

python - 如何使用 pandas Series 和 python 解决 >ValueError< ?

python-3.x - 在 Python Pandas Dataframe 中的字符串和整数列中的项目周围添加单引号

python - 即使对于 128 GB 的内存,图形聚类也会出现内存错误。为什么?

python - 类型错误 : 'Logger' object is not callable

python - 如何打开执行 python 文件的终端

python - 查找包含数据的单元格并用作数据框中的索引

python - 查找文件中重复单词的索引

python - 寻找更简单的解决方案来分组和选择 Pandas 中的行

python - Pandas 修剪数据的更好方法