从Datafram中删除方括号

2024-06-16 13:44:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧格式的adtaset,我需要从数据中删除方括号。我们该怎么办?有人能帮忙吗

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

预期产量为:

^{pr2}$

Tags: orto数据infrom格式matchengage
2条回答

假设您有这个数据帧:

df = pd.DataFrame({'Region':['New York','Los Angeles','Chicago'], 'State': ['NY [new york]', '[California]', 'IL']})

会是这样的:

^{pr2}$

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

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" \[.*\]","")

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

通过将这些应用于原始数据框上的行:

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

如果strings,则使用^{}

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

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

。。。如果lists通过^{}转换它们:

^{pr2}$

谢谢你@胡安帕.阿里维拉加如果有一个项目lists,建议:

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

相关问题 更多 >