Python 搜索字符串包含字符

Pet*_*hen 3 python regex data-manipulation pandas python-re

我有以下数据:

col1      
086945159
549615853
589ac2546
GED456231
F56hy8W12
Run Code Online (Sandbox Code Playgroud)

我想查找是否col有非数字值并返回。

col1         col2 
086945159    086945159
549615853    549615853
589ac2546    Nan
GED456231    Nan
F56hy8W12    Nan
111111111    Nan
222222222    Nan
Run Code Online (Sandbox Code Playgroud)

re.search(r'[^0-9]+', str)以前找过。但是,我如何在 in 中使用它,apply()因为如果 incol中的值具有相同的数字,例如11111111and 222222222,则这应该返回Nan.

Qua*_*ang 5

您可以使用mask条件模式:

# first part to match any non-digit
# second part to match identical characters
df['col2'] = df.col1.mask(df.col1.str.contains(r'\D|^(.)\1*$'))
Run Code Online (Sandbox Code Playgroud)

输出:

        col1       col2
0  086945159  086945159
1  549615853  549615853
2  589ac2546        NaN
3  GED456231        NaN
4  F56hy8W12        NaN
5  111111111        NaN
6  222222222        NaN
Run Code Online (Sandbox Code Playgroud)