【发布时间】:2022-01-20 12:21:35
【问题描述】:
我需要使用正则表达式和str.extract() 将一列分成两部分(假设这是最好的)
df = pd.DataFrame({
'Product': ['Truly Mix 2/12Pk Cans - 12Z',
'Bud 16Z - LOOSE - 16Z',
'Blue Moon (Case 12x - 22Z)',
'2 for the show (6/4PK - 16Z)']
})
我想要这个结果:
df_result = pd.DataFrame({
'Product': ['Truly Mix', 'Bud', 'Blue Moon', '2 for the show'],
'Packaging': ['2/12Pk Cans - 12Z',
'16Z - LOOSE - 16Z',
'Case 12x - 22Z',
'6/4PK - 16Z' ]
})
我尝试了很多东西,但仍然在使用正则表达式时遇到了困难,即使经过大量的在线学习。
这是我获得产品的最后尝试:
pattern = r'(\D+)[^\w][^(Case][^0-9]'
df['Product'] = df['Product'].str.extract(pattern)
str.replace() 应该可以很好地摆脱括号,只是不能走那么远。
我只是在 3 小时后还没有关闭。
【问题讨论】: