我有一个Python数据框,其中包含一个名为" SEGMENT"的列。我想把这个专栏分成三列。请查看以黄色突出显示的所需输出。
以下是我尝试过的代码。不幸的是,我甚至无法获得第一个替换语句。 :不会被 - 取代 - 。任何帮助是极大的赞赏!
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(':'))))
答案 0 :(得分:2)
<强>设置强>
df = pd.DataFrame({'SEGMENT': {0: 'Hight:33-48', 1: 'Hight:33-48', 2: 'Very Hight:80-88'}})
df
Out[17]:
SEGMENT
0 Hight:33-48
1 Hight:33-48
2 Very Hight:80-88
<强>解决方案强>
使用split将列拆分为3个部分,然后展开以创建新的DF。
df.SEGMENT.str.split(':|-',expand=True)\
.rename(columns=dict(zip(range(3),\
['SEGMENT','SEGMENT RANGE LOW','SEGMENT RANGE HIGH'])))
Out[13]:
SEGMENT SEGMENT RANGE LOW SEGMENT RANGE HIGH
0 Hight 33 48
1 Hight 33 48
2 Very Hight 80 88
答案 1 :(得分:2)
:
或(|)
\s*-\s*
使用str.split
(\s*
表示零个或多个空格):
df = pd.DataFrame({'SEGMENT': ['Hight: 33 - 48', 'Hight: 33 - 48', 'Very Hight: 80 - 88']})
cols = ['SEGMENT','SEGMENT RANGE LOW','SEGMENT RANGE HIGH']
df[cols] = df['SEGMENT'].str.split(':\s*|\s*-\s*',expand=True)
print (df)
SEGMENT SEGMENT RANGE LOW SEGMENT RANGE HIGH
0 Hight 33 48
1 Hight 33 48
2 Very Hight 80 88
str.extract
的解决方案:
cols = ['SEGMENT','SEGMENT RANGE LOW','SEGMENT RANGE HIGH']
df[cols] = df['SEGMENT'].str.extract('([A-Za-z\s*]+):\s*(\d+)\s*-\s*(\d+)', expand = True)
print (df)
SEGMENT SEGMENT RANGE LOW SEGMENT RANGE HIGH
0 Hight 33 48
1 Hight 33 48
2 Very Hight 80 88
答案 2 :(得分:2)
因为我喜欢命名str.extract
正则表达式
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']})
答案 3 :(得分:0)
columns = ['SEGMENT', 'SEGMENT RANGE LOW', 'SEGMENT RANGE HIGH']
df['temp'] = df['SEGMENT'].str.replace(': ','-').str.split('-')
for i, c in enumerate(columns):
df[c] = df['temp'].apply(lambda x: x[i])
del df['temp']
用连字符替换冒号,然后在连字符上拆分以获取3列的值列表。然后为3列中的每列分配值并删除临时列。
答案 4 :(得分:0)
我会使用正则表达式使用正则表达式
执行此操作df.SEGMENT.str.extract('([A-Za-z ]+):(\d+)-(\d+)', expand = True).rename(columns = {0: 'SEGMENT', 1: 'SEGMENT RANGE LOW', 2: 'SEGMENT RANGE HIGH'})
SEGMENT SEGMENT RANGE LOW SEGMENT RANGE HIGH
0 High 33 48
1 High 33 48
2 Very High 80 88