首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫str.split()函数

熊猫str.split()函数
EN

Stack Overflow用户
提问于 2018-06-22 08:19:35
回答 1查看 215关注 0票数 1

假设我有一个具有不同名称的dataFrame,一些有两个单词名,有些有一个单词名:

代码语言:javascript
复制
 Team A
 1   Zeus Odin John Wick Jason Bourne Loki
 2   

我想得到一个结果

代码语言:javascript
复制
Team A Hero 1    Team A Hero 2    Team A Hero 3   Team A Hero 4   Team A Hero 5
    Zeus             Odin           John Wick     Jason Bourne    Loki

在这样做的过程中,我将如何使用带正则表达式的str.split()函数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-22 14:34:23

一种方法可以是用没有空格的名称临时替换包含空格的女主人公的名字,并在使用您想要使用的str.split()函数后进行反转。

代码语言:javascript
复制
import re
# create dictionary to assign the name of the hero with space to the one without
dict_hero = { hero: hero.replace(' ','')  for hero in HeroList if ' ' in hero}
# create the inverse of the previous dictionary, several ways but I choose this one
dict_hero_rev = { hero.replace(' ',''):hero  for hero in HeroList if ' ' in hero}
# now create the pattern and the replacement function to use in str.replace
pat = re.compile('|'.join(dict_hero.keys())) #look for the hero's name in your dict_heor keys
repl = lambda x: dict_hero[x.group()] # replace by the corresponding name in the dict_hero
# work on the column Team A
(df['Team A'].str.replace(pat, repl) #change the one with space to without
             .str.split(' ', expand=True) # split on whitespace and expand to columns
             .replace(dict_hero_rev) # replace the hero's names missing a space by the name with space
              .rename(columns={nb: 'Team A Hero {}'.format(nb+1) for nb in range(5)}))

像这样的数据

代码语言:javascript
复制
df = pd.DataFrame({'Team A':['Zeus Odin John Wick Jason Bourne Loki',
                             'Hulk Thor Green Lantern Batman Captain America']})

                                           Team A
0           Zeus Odin John Wick Jason Bourne Loki
1  Hulk Thor Green Lantern Batman Captain America

还有一张英雄名单

代码语言:javascript
复制
HeroList = ['Green Lantern', 'Thor', 'Hulk', 'Odin', 'Batman', 
              'Jason Bourne', 'Loki', 'John Wick', 'Zeus', 'Captain America']

然后,上面的方法给出了:

代码语言:javascript
复制
  Team A Hero 1 Team A Hero 2  Team A Hero 3 Team A Hero 4    Team A Hero 5
0          Zeus          Odin      John Wick  Jason Bourne             Loki
1          Hulk          Thor  Green Lantern        Batman  Captain America
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50983642

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档