我试图只从df列中删除带整数的括号。如果它是一个对象,那么我希望保留它。我只想去掉那些都是整数的括号。
df = pd.DataFrame({
'col': ['Bear (123)', 'Dog (No 2a) (1502)', 'Cat Dog (No 7b) (16772)', 'Bear (123)']})
df['col'] = df['col'].str.replace(r"(.*)","")
预定输出:
col
0 Bear
1 Dog (No 2a)
2 Cat Dog (No 7b)
3 Bear
您可以使用:
df['col'] = df['col'].str.replace(r's*(d*)', '', regex=True)
输出:
col
0 Bear
1 Dog (No 2a)
2 Cat Dog (No 7b)
3 Bear
regex演示
s* # match spaces (optional)
( # match literal (
d* # match zero or more digits (use d+ to force at least 1 digit)
) # match literal )
注意。使用regex=True
来避免将来的警告
使用s*
匹配括号前后的可选空格,使用d+
匹配整数:
df['col'] = df['col'].str.replace(r"s*(d+)s*","", regex=True)
print (df)
col
0 Bear
1 Dog (No 2a)
2 Cat Dog (No 7b)
3 Bear