从数据框中删除方括号

4

我有一个数据集,格式为dataframe,并且其中包含方括号,我需要将数据中的方括号去除。请问应该如何处理?

   From             TO
   [wrestle]        engage in a wrestling match
   [write]          communicate or express by writing
   [write]          publish
   [spell]          write
   [compose]        write music

预期输出为:
   From             TO
   wrestle      engage in a wrestling match
   write       communicate or express by writing
   write       publish
   spell       write
2个回答

4
假设您有以下数据框:
df = pd.DataFrame({'Region':['New York','Los Angeles','Chicago'], 'State': ['NY [new york]', '[California]', 'IL']})

这将会像这样:
        Region          State
0     New York  NY [new york]
1  Los Angeles   [California]
2      Chicago             IL

只需删除方括号,您需要以下行:

df['State'] = df['State'].str.replace(r"\[","")
df['State'] = df['State'].str.replace(r"\]","")

结果如下:
        Region        State
0     New York  NY new york
1  Los Angeles   California
2      Chicago           IL

如果您想删除方括号及其中的所有内容:
df['State'] = df['State'].str.replace(r"\[.*\]","")
df['State'] = df['State'].str.replace(r" \[.*\]","")

第一行代码删除方括号中的字符,第二行代码考虑了字符前面的空格,为确保安全起见,最好同时运行这两行代码。

将这两行代码应用于原始数据框 df:

        Region State
0     New York    NY
1  Los Angeles      
2      Chicago    IL

3

如果需要处理字符串,可以使用str.strip函数:

print (type(df.loc[0, 'From']))
<class 'str'>

df['From'] = df['From'].str.strip('[]')

...如果涉及到list,则使用str.join进行转换:

print (type(df.loc[0, 'From']))
<class 'list'>

df['From'] = df['From'].str.join(', ')

感谢 @juanpa.arrivillaga 提出的建议,如果有一个项目 列表

df['From'] = df['From'].str[0]

可以通过以下方式进行检查:

print (type(df.loc[0, 'From']))
<class 'list'>

print (df['From'].str.len().eq(1).all())
True

print (df)
      From                                 TO
0  wrestle        engage in a wrestling match
1    write  communicate or express by writing
2    write                            publish
3    spell                              write
4  compose                        write music

1
如果确实所有的“list”都只有一个值,那么也可以使用“df.From.str[0]”。 - juanpa.arrivillaga
@juanpa.arrivillaga - 感谢您的建议。 - jezrael
@jezrael 我有一个问题,是否可以将 df['From'] = df['From'].str.strip('[]') 应用于整个数据框,而不是逐列单独执行? - 1muflon1
@1muflon1- 是的,请使用这个 - jezrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接