我有一个熊猫DataFrame,其中包含一列字符串值。我需要根据部分字符串匹配来选择行。
类似于这个成语:
re.search(pattern, cell_in_question)
返回布尔值。我熟悉df[df['A']==“helloworld”]的语法,但似乎找不到一种方法来处理部分字符串匹配,比如“hello”。
我有一个熊猫DataFrame,其中包含一列字符串值。我需要根据部分字符串匹配来选择行。
类似于这个成语:
re.search(pattern, cell_in_question)
返回布尔值。我熟悉df[df['A']==“helloworld”]的语法,但似乎找不到一种方法来处理部分字符串匹配,比如“hello”。
当前回答
这是我最后为部分字符串匹配所做的。如果有人有更有效的方法,请告诉我。
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
其他回答
如果有人想知道如何执行相关问题:“按部分字符串选择列”
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)
我在ipython笔记本电脑的macos上使用熊猫0.14.1。我尝试了上面的建议行:
df[df["A"].str.contains("Hello|Britain")]
并得到一个错误:
无法使用包含NA/NaN值的矢量进行索引
但当添加了“==True”条件时,效果非常好,如下所示:
df[df['A'].str.contains("Hello|Britain")==True]
这是我最后为部分字符串匹配所做的。如果有人有更有效的方法,请告诉我。
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
如果需要对panda数据帧列中的字符串进行不区分大小写的搜索:
df[df['A'].str.contains("hello", case=False)]
我的2c价值:
我执行了以下操作:
sale_method = pd.DataFrame(model_data['Sale Method'].str.upper())
sale_method['sale_classification'] = \
np.where(sale_method['Sale Method'].isin(['PRIVATE']),
'private',
np.where(sale_method['Sale Method']
.str.contains('AUCTION'),
'auction',
'other'
)
)