2017-01-16 51 views
1

我有一个需要搜索分号的熊猫数据框(df)。我第一次尝试用熊猫 - 在数据框中搜索字符

semicolon_check = df.to_string().__contains__(';')

但它是非常缓慢的,并在大DataFrames的情况下,我碰到一个内存错误。然后我试图遍历列与.str,但不是所有列都是字符串所以每当我达到我收到了一条错误

AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

所以我结束了这段代码

for col in df.columns: if df[col].dtype == 'O': if df[col].str.contains(r';').any(): print 'found in ' + col

数字列

有没有更简单的方法来实现目标?以上所述虽然按预期工作似乎对于像价值搜索这样的基本任务来说有点过分了。

+0

这可能不是最有效的方法,但它可以安全地循环:'df.applymap(lambda x:“;”in str(x))''。 – Abdou

回答

5

您可以只过滤字符串中使用select_dtypes然后列调用apply,并通过一个lambda调用str.containsany

In [33]: 
# create a test df 
df = pd.DataFrame({'int':np.arange(5), 'str':['a','a;a',';','b','c'], 'flt':np.random.randn(5), 'other str':list('abcde')}) 
df 

Out[33]: 
     flt int other str str 
0 1.020561 0   a a 
1 0.022842 1   b a;a 
2 -1.207961 2   c ; 
3 1.092960 3   d b 
4 -1.560300 4   e c 

In [35]: 
# filter on dtype 
test = df.select_dtypes([np.object]).apply(lambda x: x.str.contains(';').any()) 
test 

Out[35]: 
other str False 
str   True 
dtype: bool 

我们可以使用从过滤柱阵列DF与面罩一起过滤cols:

In [36]: 
# we can use the above to mask the columns 
str_cols = df.select_dtypes([np.object]).columns 
str_cols[test] 

Out[36]: 
Index(['str'], dtype='object')