Python:使用Lambda将字符串字段拆分为3个单独的字段 [英] Python: Split a String Field into 3 Separate Fields using Lambda

查看:355
本文介绍了Python:使用Lambda将字符串字段拆分为3个单独的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python数据框,其中包含一个名为"SEGMENT"的列.我想将该列分为三列.请以黄色突出显示我想要的输出.

I have a Python data frame which includes a column called "SEGMENT". I want to break the column up into three columns. Please see my desired output highlighted in yellow.

下面是我尝试过的代码.不幸的是,我什至无法获得第一个replace语句. :不会被-代替.任何帮助是极大的赞赏!

Below is the code I have tried. Unfortunately I can't even get the first replace statement to work. The : does not get replaced by -. Any help is greatly appreciated!

df_stack_ranking['CURRENT_AUM_SEGMENT'] = df_stack_ranking['CURRENT_AUM_SEGMENT'].replace(':', '-')

s = df_stack_ranking['CURRENT_AUM_SEGMENT'].str.split(' ').apply(Series, 1).stack()

s.index = s.index.droplevel(-1)

s.name = 'SEGMENT'

df_stack_ranking.join(s.apply(lambda x: Series(x.split(':'))))

推荐答案

因为我喜欢用str.extract正则表达式命名列

Because I like naming columns from the str.extract regex

regex = '\s*(?P<SEGMENT>\S+)\s*:\s*(?P<SEGMENT_RANGE_LOW>\S+)\s*-\s*(?P<SEGMENT_RANGE_HIGH>\S+)\s*'
df.SEGMENT.str.extract(regex, expand=True)

  SEGMENT SEGMENT_RANGE_LOW SEGMENT_RANGE_HIGH
0    High                33                 48
1    High                33                 48
2    High                80                 88


设置

df = pd.DataFrame({'SEGMENT': ['High: 33 - 48', 'High: 33 - 48', 'Very High: 80 - 88']})

这篇关于Python:使用Lambda将字符串字段拆分为3个单独的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆