Python 3.x 使用多个分隔符将一列拆分为多列
给出如下数据帧:Python 3.x 使用多个分隔符将一列拆分为多列,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,给出如下数据帧: player score 0 Sergio Agüero Forward — Manchester City 209.98 1 Eden Hazard Midfield — Chelsea 274.04 2 Alexis Sánchez Forward — Arsenal 223.86 3 Yaya Touré Midfield
player score
0 Sergio Agüero Forward — Manchester City 209.98
1 Eden Hazard Midfield — Chelsea 274.04
2 Alexis Sánchez Forward — Arsenal 223.86
3 Yaya Touré Midfield — Manchester City 197.91
4 Angel María Midfield — Manchester United 132.23
如何将球员分成三个新的栏名、位置和球队
我考虑过用df['name_position','team']=df['player'].str.splitpat='-',expand=True将其拆分为两列,然后将name_position拆分为name和position。但是有更好的解决办法吗
非常感谢。您可以使用string.split按空格分割python字符串。这会将您的文本分解为“单词”,然后您只需访问您喜欢的单词,如下所示:
string = "Sergio Agüero Forward — Manchester City"
name = string.split()[0]
position = string.split()[2]
team = string.split()[4] + (string.split().has_key(5) ? string.split()[5] : '')
对于更复杂的模式,可以使用regex,它是一个强大的字符串模式查找工具
希望这有所帮助:您可以使用string.split按空格分割python字符串。这会将您的文本分解为“单词”,然后您只需访问您喜欢的单词,如下所示:
string = "Sergio Agüero Forward — Manchester City"
name = string.split()[0]
position = string.split()[2]
team = string.split()[4] + (string.split().has_key(5) ? string.split()[5] : '')
对于更复杂的模式,可以使用regex,它是一个强大的字符串模式查找工具
希望这有帮助:如果您想一次完成,也可以使用str.extract:
print(df["player"].str.extract(r"(?P<name>.*?)\s.*?\s(?P<position>[A-Za-z]+)\s—\s(?P<team>.*)"))
name position team
0 Sergio Forward Manchester City
1 Eden Midfield Chelsea
2 Alexis Forward Arsenal
3 Yaya Midfield Manchester City
4 Angel Midfield Manchester United
如果要一次性完成,也可以使用str.extract:
print(df["player"].str.extract(r"(?P<name>.*?)\s.*?\s(?P<position>[A-Za-z]+)\s—\s(?P<team>.*)"))
name position team
0 Sergio Forward Manchester City
1 Eden Midfield Chelsea
2 Alexis Forward Arsenal
3 Yaya Midfield Manchester City
4 Angel Midfield Manchester United
我认为你的解决方案很好。