英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论