我有一个熊猫DataFrame,其中包含一列字符串值。我需要根据部分字符串匹配来选择行。
类似于这个成语:
re.search(pattern, cell_in_question)
返回布尔值。我熟悉df[df['A']==“helloworld”]的语法,但似乎找不到一种方法来处理部分字符串匹配,比如“hello”。
我有一个熊猫DataFrame,其中包含一列字符串值。我需要根据部分字符串匹配来选择行。
类似于这个成语:
re.search(pattern, cell_in_question)
返回布尔值。我熟悉df[df['A']==“helloworld”]的语法,但似乎找不到一种方法来处理部分字符串匹配,比如“hello”。
当前回答
快速提示:如果要基于索引中包含的部分字符串进行选择,请尝试以下操作:
df['stridx']=df.index
df[df['stridx'].str.contains("Hello|Britain")]
其他回答
快速提示:如果要基于索引中包含的部分字符串进行选择,请尝试以下操作:
df['stridx']=df.index
df[df['stridx'].str.contains("Hello|Britain")]
矢量化字符串方法(即Series.str)允许您执行以下操作:
df[df['A'].str.contains("hello")]
这在熊猫0.8.1及以上版本中可用。
如果需要对panda数据帧列中的字符串进行不区分大小写的搜索:
df[df['A'].str.contains("hello", case=False)]
这是我最后为部分字符串匹配所做的。如果有人有更有效的方法,请告诉我。
def stringSearchColumn_DataFrame(df, colName, regex):
newdf = DataFrame()
for idx, record in df[colName].iteritems():
if re.search(regex, record):
newdf = concat([df[df[colName] == record], newdf], ignore_index=True)
return newdf
您可以尝试将它们视为字符串:
df[df['A'].astype(str).str.contains("Hello|Britain")]