如何从 Python 数据框中查找特殊字符
How to find special characters from Python Data frame
我需要从整个数据框中找到特殊字符。
在下面的数据框中,某些列包含特殊字符,如何找到哪些列包含特殊字符?
如果每列包含特殊字符,则希望显示文本。
您可以设置有效字符的字母表,例如
import string
alphabet = string.ascii_letters+string.punctuation
这是
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
并且只需使用
df.col.str.strip(alphabet).astype(bool).any()
例如,
df = pd.DataFrame({'col1':['abc', 'hello?'], 'col2': ['ÃÉG', 'Ç']})
col1 col2
0 abc ÃÉG
1 hello? Ç
然后,用上面的字母,
df.col1.str.strip(alphabet).astype(bool).any()
False
df.col2.str.strip(alphabet).astype(bool).any()
True
语句特殊字符可能非常棘手,因为它取决于您的解释。例如,您 可能 或 可能不会 将 #
视为特殊字符。此外,某些语言(例如葡萄牙语)可能有 ã
和 é
等字符,但其他语言(例如英语)则没有。
要从数据框列中删除不需要的字符,请使用正则表达式:
def strip_character(dataCol):
r = re.compile(r'[^a-zA-Z !@#$%&*_+-=|\:";<>,./()[\]{}\']')
return r.sub('', dataCol)
df[resultCol] = df[dataCol].apply(strip_character)
# Whitespaces also could be considered in some cases.
import string
unwanted = string.ascii_letters + string.punctuation + string.whitespace
print(unwanted)
# This helped me extract '10' from '10+ years'.
df.col = df.col.str.strip(unwanted)
我需要从整个数据框中找到特殊字符。
在下面的数据框中,某些列包含特殊字符,如何找到哪些列包含特殊字符?
如果每列包含特殊字符,则希望显示文本。
您可以设置有效字符的字母表,例如
import string
alphabet = string.ascii_letters+string.punctuation
这是
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
并且只需使用
df.col.str.strip(alphabet).astype(bool).any()
例如,
df = pd.DataFrame({'col1':['abc', 'hello?'], 'col2': ['ÃÉG', 'Ç']})
col1 col2
0 abc ÃÉG
1 hello? Ç
然后,用上面的字母,
df.col1.str.strip(alphabet).astype(bool).any()
False
df.col2.str.strip(alphabet).astype(bool).any()
True
语句特殊字符可能非常棘手,因为它取决于您的解释。例如,您 可能 或 可能不会 将 #
视为特殊字符。此外,某些语言(例如葡萄牙语)可能有 ã
和 é
等字符,但其他语言(例如英语)则没有。
要从数据框列中删除不需要的字符,请使用正则表达式:
def strip_character(dataCol):
r = re.compile(r'[^a-zA-Z !@#$%&*_+-=|\:";<>,./()[\]{}\']')
return r.sub('', dataCol)
df[resultCol] = df[dataCol].apply(strip_character)
# Whitespaces also could be considered in some cases.
import string
unwanted = string.ascii_letters + string.punctuation + string.whitespace
print(unwanted)
# This helped me extract '10' from '10+ years'.
df.col = df.col.str.strip(unwanted)