我有一个熊猫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[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'
)
)
假设您有以下DataFrame:
>>> df = pd.DataFrame([['hello', 'hello world'], ['abcd', 'defg']], columns=['a','b'])
>>> df
a b
0 hello hello world
1 abcd defg
您始终可以在lambda表达式中使用in运算符来创建筛选器。
>>> df.apply(lambda x: x['a'] in x['b'], axis=1)
0 True
1 False
dtype: bool
这里的技巧是在apply中使用axis=1选项,将元素逐行传递给lambda函数,而不是逐列传递。
在此之前,有一些答案可以实现所要求的功能,无论如何,我想展示最普遍的方式:
df.filter(regex=".*STRING_YOU_LOOK_FOR.*")
这样,你就可以得到你所寻找的专栏,无论它是怎么写的。
(显然,您必须为每种情况编写正确的正则表达式)
我在ipython笔记本电脑的macos上使用熊猫0.14.1。我尝试了上面的建议行:
df[df["A"].str.contains("Hello|Britain")]
并得到一个错误:
无法使用包含NA/NaN值的矢量进行索引
但当添加了“==True”条件时,效果非常好,如下所示:
df[df['A'].str.contains("Hello|Britain")==True]
快速提示:如果要基于索引中包含的部分字符串进行选择,请尝试以下操作:
df['stridx']=df.index
df[df['stridx'].str.contains("Hello|Britain")]