如何从列中提取特定文本

2024-04-20 05:08:38 发布

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

我有一个带列的pandas数据框,我需要清理它,因为数据没有必要的格式:

df = pd.DataFrame({'item': ["1","2","3","4","5","6"], 'store': ["a [note 3]","b  [note 98]","c ","a 
[note 222]","b","c"]})
print(df)

item         store
0    1    a [note 3]
1    2  b  [note 98]
2    3            c 
3    4  a [note 222]
4    5             b
5    6             c

'store'必须按如下方式更改:

 item store
0    1     a
1    2     b
2    3     c
3    4     a
4    5     b
5    6     c

Tags: 数据storedataframepandasdf格式方式item
2条回答

按开始的方括号拆分,并在结果列表中拾取第一个索引值

df['store'] = df.store.str.split('\[').str[0]

您不需要正则表达式。只需在空格上拆分,然后取第一个字符

df['store'] = df['store'].apply(lambda x: x.split()[0])

如果最终需要正则表达式,可以使用extract

df['store'] = df['store'].str.extract('^([a-z])')

如果括号前有多个字符

df['store'] = df['store'].str.extract('^(.+?)(?=\[|$)')

相关问题 更多 >