【问题标题】:How to check contents inside brackets in pandas [closed]如何检查熊猫括号内的内容[关闭]
【发布时间】:2020-01-25 15:31:08
【问题描述】:

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

  • "I am sharad my phone number is (0000000)"
  • "hi this [sharad]"
  • "{there} you go"
  • "[this is error]"

并且应该将False 给:

  • "ho ho ho"
  • "here comes santa []"
  • "{} what is this"

如果大括号内有任何内容,则返回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                          

【问题讨论】:

标签: regex python-3.x pandas


【解决方案1】:

从这些数据开始:

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

我们可以检查“brackets”,然后使用regexcontains() 方法检查它们是否包含任何内容:

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

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

Documentation for contains

regex的解释:

  • 对于[],我使用\[\] 来查找这些字符。然后在其中我使用(.+) 检查两个括号之间是否有任何东西。

我使用其他两个版本的“brackets”((){})做了同样的事情

| 是一个 or 运算符,因此 contains 知道检查任何 brackets

其他资源

【讨论】:

  • 非常感谢您拯救了这一天!!!
  • @SHARADSAURAV 不客气!这是一个有趣的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
相关资源
最近更新 更多