从中的列中删除支架

2024-03-29 01:54:21 发布

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

我有一个数据帧,其数据格式如下:

name,type
P1,["prod_1", "prod_3"]
P2,["prod_2", "prod_3"]
P3,None

我正在尝试将其转换为以下输出:

name,type
P1,"prod_1", "prod_3"
P2,"prod_2", "prod_3"
P3,None

df['type']的数据类型是object

我尝试使用正则表达式,如下所示:

df['type'] = df['type'].replace("[", df['type'])
df['type'] = df['type'].replace("]", df['type'])

但这仍然返回相同的输出,前后用括号括起来


Tags: 数据namenonedfobjecttypeprodreplace
1条回答
网友
1楼 · 发布于 2024-03-29 01:54:21

用这个

df['type']=df['type'].str.replace('\[|\]','')

订单号:

  name                type
0   P1  'prod_1', 'prod_3'
1   P2  'prod_2', 'prod_3'
2   P3                None

文件:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html

str.replace接收regex作为替换模式,|在这里用作or\转义字符在这里用来区别regex字符

正如@Jon Clements所说,strip将是解决这个问题的最佳选择。你知道吗

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

相关问题 更多 >