我有一个 DataFrame 有4列,其中2列包含字符串值 . 我想知道是否有一种方法可以根据与特定列的部分字符串匹配来选择行?
DataFrame
换句话说,函数或lambda函数会做类似的事情
re.search(pattern, cell_in_question)
返回一个布尔值 . 我熟悉 df[df['A'] == "hello world"] 的语法,但似乎无法找到一种方法来做同样的部分字符串匹配说 'hello' .
df[df['A'] == "hello world"]
'hello'
有人能指出我正确的方向吗?
基于github问题#620,看起来你很快就能做到以下几点:
df[df['A'].str.contains("hello")]
更新:vectorized string methods (i.e., Series.str)在pandas 0.8.1及更高版本中可用 .
我在ipython笔记本上的macos上使用pandas 0.14.1 . 我尝试了上面的提议行:
df[df['A'].str.contains("Hello|Britain")]
并得到一个错误:
"cannot index with vector containing NA / NaN values"
但是当添加“== True”条件时它完美地工作,如下所示:
df[df['A'].str.contains("Hello|Britain")==True]
如果有人想知道如何执行相关问题: "Select column by partial string"
使用:
df.filter(like='hello') # select columns which contain the word hello
要通过部分字符串匹配选择行,请将 axis=0 传递给过滤器:
axis=0
# selects rows which contain the word hello in their index label df.filter(like='hello', axis=0)
快速注意:如果要根据索引中包含的部分字符串进行选择,请尝试以下操作:
df['stridx']=df.index df[df['stridx'].str.contains("Hello|Britain")]
假设您有以下 DataFrame :
>>> df = pd.DataFrame([['hello', 'hello world'], ['abcd', 'defg']], columns=['a','b']) >>> df a b 0 hello hello world 1 abcd defg
您始终可以在lambda表达式中使用 in 运算符来创建过滤器 .
in
>>> df.apply(lambda x: x['a'] in x['b'], axis=1) 0 True 1 False dtype: bool
这里的技巧是使用 apply 中的 axis=1 选项逐行将元素传递给lambda函数,而不是逐列传递 .
apply
axis=1
这是我最终为部分字符串匹配做的事情 . 如果有人有更有效的方式这样做,请告诉我 .
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
import pandas as pd k=pd.DataFrame(['hello','doubt','hero','help']) k.columns=['some_thing'] t=k[k['some_thing'].str.contains("hel")] d=k.replace(t,'CS')
:::OUTPUT:::
k Out[95]: some_thing 0 hello 1 doubt 2 hero 3 help t Out[99]: some_thing 0 hello 3 help d Out[96]: some_thing 0 CS 1 doubt 2 hero 3 CS
你会怎样过滤掉“自由”,除了更多的标准,如“遗产”,“ulic”等 .
df_Fixed[~df_Fixed["Busler Group"].map(lambda x: x.startswith('Liberty'))]
8 回答
基于github问题#620,看起来你很快就能做到以下几点:
更新:vectorized string methods (i.e., Series.str)在pandas 0.8.1及更高版本中可用 .
我在ipython笔记本上的macos上使用pandas 0.14.1 . 我尝试了上面的提议行:
并得到一个错误:
但是当添加“== True”条件时它完美地工作,如下所示:
如果有人想知道如何执行相关问题: "Select column by partial string"
使用:
要通过部分字符串匹配选择行,请将
axis=0
传递给过滤器:快速注意:如果要根据索引中包含的部分字符串进行选择,请尝试以下操作:
假设您有以下
DataFrame
:您始终可以在lambda表达式中使用
in
运算符来创建过滤器 .这里的技巧是使用
apply
中的axis=1
选项逐行将元素传递给lambda函数,而不是逐列传递 .这是我最终为部分字符串匹配做的事情 . 如果有人有更有效的方式这样做,请告诉我 .
:::OUTPUT:::
你会怎样过滤掉“自由”,除了更多的标准,如“遗产”,“ulic”等 .