我确信对于正则表达式来说,这是一个非常简单的问题,但是:尝试在pandas中使用str.match来匹配非ASCII码字符(时代符号)。我期望第一个匹配调用将匹配DataFrame的第一行;第二个匹配调用将匹配最后一行;第三个匹配将匹配第一行和最后一行。但是,第一个调用确实匹配,但第二个和第三个调用不匹配。我哪里错了?
Dataframe看起来像这样(用x代替了时间符号,它实际上打印成一个?):
Column
0 2x 32
1 42
2 64 x2Pandas 0.20.3,python 2.7.13,OS X.
#!/usr/bin/env python
import pandas as pd
import re
html = '<table><thead><tr><th>Column</th></tr></thead><tbody><tr><td>2× 32</td></tr><tr><td>42</td></tr><tr><td>64 ×2</td></tr></tbody><table>'
df = pd.read_html(html)[0]
print df
print df[df['Column'].str.match(ur'^[2-9]\u00d7', re.UNICODE, na=False)]
print df[df['Column'].str.match(ur'\u00d7[2-9]$', re.UNICODE, na=False)]
print df[df['Column'].str.match(ur'\u00d7', re.UNICODE, na=False)]我看到的输出(还是用?替换为x):
Column
0 2x 32
Empty DataFrame
Columns: [Column]
Index: []
Empty DataFrame
Columns: [Column]
Index: []发布于 2017-08-27 06:41:14
df.Column.str.contains(r'^[2-9]\u00d7')
0 True
1 False
2 False
Name: Column, dtype: bool
df.Column.str.contains(r'\u00d7[2-9]$')
0 False
1 False
2 True
Name: Column, dtype: bool
df.Column.str.contains(r'\u00d7')
0 True
1 False
2 True
Name: Column, dtype: bool说明:contains()使用re.search(),match()使用re.match() (docs)。因为re.match()只从字符串的开头匹配(docs),所以只有在开头匹配的第一个大小写(使用^)才有效。实际上,在这种情况下,您不需要同时使用match和^
df.Column.str.match(r'[2-9]\u00d7')
0 True
1 False
2 False
Name: Column, dtype: boolhttps://stackoverflow.com/questions/45900187
复制相似问题