首页 > 解决方案 > 过滤数据框中包含某个特定字符串的行

问题描述

我有一个像这个例子这样的数据框:我只想过滤包含或以“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

标签: pythonpandas

解决方案


编辑: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

推荐阅读