2017-01-16 50 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')