移除 Pandas 中方括号括起来的文本。

huangapple go评论126阅读模式
英文:

Remove texts that are enclosed in square brackets in Pandas

问题

Sure, here's the translated code-related part:

我想知道如何遍历一列并删除方括号内的字符串

示例

'字符串 [更多字符串]'

之后

'字符串'

有人能帮我吗

我考虑使用正则表达式然而我不知道如何缩小范围我认为可以通过编写一个 lambda 函数来完成
英文:

I would like to know how I can go through a column and remove the strings that are between square brackets.

Example

'String [more string]'

after

'String'

Can anyone help me?

I thought about using regular expressions. However, I don't know how to zoom in. I think it can be done by writing a lambda function.

答案1

得分: 0

你可以这样做

import pandas as pd
df = pd.DataFrame({'col1':['String [more string]']})
df['col2'] = df['col1'].str.replace(r'\[.*\]', '', regex=True)
print(df)

输出如下

                   col1    col2
0  String [more string]  String

请注意,我们需要转义 [ 以获取字面的 [,否则 [ 具有特殊含义。

英文:

You might do it following way

import pandas as pd
df = pd.DataFrame({'col1':['String [more string]']})
df['col2'] = df['col1'].str.replace(r'\[.*\]', '', regex=True)
print(df)

gives output

                   col1     col2
0  String [more string]  String 

Observe we need to escape [ to get literal [ as [ has special meaning otherwise.

huangapple
  • 本文由 发表于 2023年3月7日 04:28:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定