我有一个熊猫DataFrame,其中包含一列字符串值。我需要根据部分字符串匹配来选择行。
类似于这个成语:
re.search(pattern, cell_in_question)
返回布尔值。我熟悉df[df['A']==“helloworld”]的语法,但似乎找不到一种方法来处理部分字符串匹配,比如“hello”。
我有一个熊猫DataFrame,其中包含一列字符串值。我需要根据部分字符串匹配来选择行。
类似于这个成语:
re.search(pattern, cell_in_question)
返回布尔值。我熟悉df[df['A']==“helloworld”]的语法,但似乎找不到一种方法来处理部分字符串匹配,比如“hello”。
当前回答
如果有人想知道如何执行相关问题:“按部分字符串选择列”
Use:
df.filter(like='hello') # select columns which contain the word hello
若要通过部分字符串匹配来选择行,请将axis=0传递到筛选器:
# selects rows which contain the word hello in their index label
df.filter(like='hello', axis=0)
其他回答
如果有人想知道如何执行相关问题:“按部分字符串选择列”
Use:
df.filter(like='hello') # select columns which contain the word hello
若要通过部分字符串匹配来选择行,请将axis=0传递到筛选器:
# selects rows which contain the word hello in their index label
df.filter(like='hello', axis=0)
如果需要对panda数据帧列中的字符串进行不区分大小写的搜索:
df[df['A'].str.contains("hello", case=False)]
对于包含特殊字符的字符串,使用contains效果不佳。尽管找到了工作。
df[df['A'].str.find("hello") != -1]
您可以尝试将它们视为字符串:
df[df['A'].astype(str).str.contains("Hello|Britain")]
假设我们在数据帧df中有一个名为“ENTITY”的列。我们可以过滤df,以获得整个数据帧df,其中“实体”列的行不包含“DM”,方法如下:
mask = df['ENTITY'].str.contains('DM')
df = df.loc[~(mask)].copy(deep=True)