Regex 如何检查熊猫中括号内的内容

Regex 如何检查熊猫中括号内的内容,regex,python-3.x,pandas,Regex,Python 3.x,Pandas,我需要一个表达式来检查大括号内是否有任何内容(“大括号”可以是(),{},[])中的任意一个。例如,它应该为这些字符串提供True: “我是沙拉德,我的电话号码是(0000000)” “你好,我是[sharad]” “{there}你走吧” “[这是错误]” 并应将设置为False: “呵呵呵呵” “圣诞老人[]来了” “{}这是什么” 如果大括号内有任何内容,则返回True,否则返回False。我是Python新手,提前感谢您的帮助 例如: df = pd.read_excel(fil

我需要一个表达式来检查大括号内是否有任何内容(“大括号”可以是
()
{}
[]
)中的任意一个。例如,它应该为这些字符串提供
True

  • “我是沙拉德,我的电话号码是(0000000)”
  • “你好,我是[sharad]”
  • “{there}你走吧”
  • “[这是错误]”
并应将
设置为False

  • “呵呵呵呵”
  • “圣诞老人[]来了”
  • “{}这是什么”
如果大括号内有任何内容,则返回
True
,否则返回
False
。我是Python新手,提前感谢您的帮助

例如:

df = pd.read_excel(file)
df.index = range(2,df.shape[0]+2)
for index,row in df.iterrows():
    if(row['column_name']******) # expression to check if there is any 
                                 # content inside brackets content could be 
                                 # nan, string or a number                          

从这些数据开始:

import pandas as pd

df = pd.DataFrame({
    'col' : [
        "I am sharad my phone number is (0000000)",
        "hi this [sharad]",
        "{there} you go",
        "[this is error]",
        "ho ho ho",
        "here comes santa []",
        "{} what is this",
    ]
})

print(df)

                                        col
0  I am sharad my phone number is (0000000)
1                          hi this [sharad]
2                            {there} you go
3                           [this is error]
4                                  ho ho ho
5                       here comes santa []
6                           {} what is this
我们可以检查“
括号
”,然后使用
regex
contains()
方法检查它们是否包含任何内容:

print(df.col.str.contains('\[(.+)\]|\((.+)\)|\{(.+)\}'))

0     True
1     True
2     True
3     True
4    False
5    False
6    False
Name: col, dtype: bool

regex的解释

  • 对于
    []
    ,我使用
    \[
    \]
    来查找这些字符。然后在它们内部,我使用了
    (.+)
    ,检查两个括号之间是否有任何内容
我也使用了“
方括号
”的另外两个版本(
()
{}

|
是or运算符,因此
包含的
知道检查是否有任何
括号

其他资源


你好。请花点时间阅读这篇文章,以及如何提供答案,并相应地修改你的问题。这些提示可能也很有用。谢谢你,我这么做了,它肯定会有帮助是的,最好的办法是删除问题并创建另一个问题,同时添加新标签
regex
谢谢你挽救了这一天@沙拉德沙拉夫,不客气!这是一个有趣的问题。