假设我有一个具有不同名称的dataFrame,一些有两个单词名,有些有一个单词名:
Team A
1 Zeus Odin John Wick Jason Bourne Loki
2 我想得到一个结果
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()函数?
发布于 2018-06-22 14:34:23
一种方法可以是用没有空格的名称临时替换包含空格的女主人公的名字,并在使用您想要使用的str.split()函数后进行反转。
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)}))像这样的数据
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还有一张英雄名单
HeroList = ['Green Lantern', 'Thor', 'Hulk', 'Odin', 'Batman',
'Jason Bourne', 'Loki', 'John Wick', 'Zeus', 'Captain America']然后,上面的方法给出了:
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 Americahttps://stackoverflow.com/questions/50983642
复制相似问题