python - 过滤数据框中包含某个特定字符串的行
问题描述
我有一个像这个例子这样的数据框:我只想过滤包含或以“Python”(小写或大写)单词开头的行(注意..在我的常规数据框中,列数和行数可能会有所不同)
df = pd.DataFrame({ "A": ['Python is Cool', 5, 6, 7,8,9,10,11],
"B": ['w', 'x', 'y', 'z','w', 'x', 'y', 'z'],
"C": ['a', 'b', 'c', 'd','e','f','..PYTHON','test'],
"D": ['q', 'r', 's', 't','q', 'r', 's', 't'],
"X": ["B", "A", "D", "B", 'Pi','ABC','CD','2234'],
"Y": ["B,C", "A,B", "C,D", "A,B","B,C", "A,B", "C,D", "A,B"],
"Z": ["B,C", "A,B", "test Python", "A,B","B,C", "A,B", "C,D", "A,B"]
})
输出应在此数据帧行(0、2 和 6)中返回/过滤:
0 **Python is Cool** w a q B B,C B,C
2 6 y c s D C,D **test Python**
6 10 y **..PYTHON** s CD C,D C,D
解决方案
编辑:Python 3.7 版
这将通过任意字符串过滤行。使用 DataFrame 方法可能有更有效的方法,但这至少可以工作。
它遍历所有行,然后为每一行遍历列以查找特定字符串。如果它在一行中找到字符串,它将跳到下一行。最坏的情况是它会遍历框架中的所有项目。
def filterDfByRow(df, string):
toReturn = []
for i in range(len(df)):
for col in df.columns:
item = df[col][i]
if string.lower() in str(item).lower():
toReturn.append(i)
break
return df.filter(items=toReturn, axis=0)
df = pd.DataFrame({ "A": ['Python is Cool', 5, 6, 7,8,9,10,11],
"B": ['w', 'x', 'y', 'z','w', 'x', 'y', 'z'],
"C": ['a', 'b', 'c', 'd','e','f','..PYTHON','test'],
"D": ['q', 'r', 's', 't','q', 'r', 's', 't'],
"X": ["B", "A", "D", "B", 'Pi','ABC','CD','2234'],
"Y": ["B,C", "A,B", "C,D", "A,B","B,C", "A,B", "C,D", "A,B"],
"Z": ["B,C", "A,B", "test Python", "A,B","B,C", "A,B", "C,D", "A,B"]
})
filteredDf = filterDfByRow(df, 'python')
print(filteredDf)
下面是这个脚本的输出
A B C D X Y Z
0 Python is Cool w a q B B,C B,C
2 6 y c s D C,D test Python
6 10 y ..PYTHON s CD C,D C,D
推荐阅读
- node.js - VS Code NodeJS 调试命中断点但不允许步进代码
- mongodb - 从包含约 120 万条记录的集合中,Mongo 查找查询失败
- c# - 如何在 VS2019 XAML 设计器(UWP)中隐藏网格线?
- html - Vue在动态呈现的组件上创建结束标签,用结束标签关闭无效元素是有效的html吗?
- excel - VBA XML:查找多个命名空间的根节点
- javascript - 如何在 div 标签上使用 onclick
- python - 使用 xlrd 和 openpyxl 与 Azure Rights Management Service (Azure RMS) 读取 excel 文件
- oaf - OAF 如何对齐字段
- nginx - nginx 子目录重定向到根目录
- node.js - Firebase 魔术电子邮件链接和密码登录