2017-05-29 61 views
2

如何在使用熊貓的每一列上搜索字符串值。 可以說我有32列,如何使用熊貓在整個數據框中搜索部分字符串?

df[df['A'].str.contains("hello")] 

這個返回值是否出現在「A」柱與否,如何每列中的值是存在的行上進行搜索。 數據集:

A   B   C 
1   hi   hie 
2   bye   Hello 

如果我搜索 「你好」 或 「Hello」 的輸出應該是:

A   B   C 
2   bye   Hello 

回答

2

我認爲你可以使用:

df = pd.DataFrame({'A':['hello fgf','s','f'],'B':['d','ff hello','f'],'C':[4,7,8]}) 
print (df) 
      A   B C 
0 hello fgf   d 4 
1   s ff hello 7 
2   f   f 8 

mask = df.applymap(lambda x: 'hello' in str(x)) 
print (mask) 
     A  B  C 
0 True False False 
1 False True False 
2 False False False 

然後,如果需要過濾器添加any檢查至少一個True每行boolean indexing

df1 = df[mask.any(axis=1)] 
print (df1) 
      A   B C 
0 hello fgf   d 4 
1   s ff hello 7 

編輯:

tested = 'hello' 
mask = df.applymap(lambda x: tested.lower() in str(x).lower()) 
print (mask) 
     A  B  C 
0 False False False 
1 False False True 
+0

「類型錯誤:(「類型'float'的參數不可迭代',在索引Account_Name'發生') [完成於0.3s退出代碼1]「---->出現此錯誤。 – Sidhartha

+0

區分大小寫。如何解決區分大小寫的部分? – Sidhartha

+0

你認爲不敏感嗎?你可以給我的樣品,並添加它的問題? – jezrael

1

您也可以連接所有列成一個字符串,並在連接字符串搜索您的字符串:

In [21]: df[df.astype(str).add('|').sum(1).str.contains('hello')] 
Out[21]: 
      A   B C 
0 hello fgf   d 4 
1   s ff hello 7 

說明:

In [22]: df.astype(str).add('|').sum(1) 
Out[22]: 
0 hello fgf|d|4| 
1  s|ff hello|7| 
2   f|f|8| 
dtype: object 
相關問題