Pandas把一对中的每一个成员加在一列中

2024-03-29 14:43:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

eventScore
5-4 
6-2 6-0
6-2 6-3
7-6 6-2
2-6 4-6
1-6 1-3 

每对的左边是球员得分,右边是对手得分。你知道吗

所以对于每一列,我需要加上左边的破折号和右边的破折号。你知道吗

最终输出:

eventScore     playerScore   opponentScore
5-4            5             4
6-2 6-0        12            2  
6-2 6-3        12            5
7-6 6-2        13            8
2-6 4-6        6             12
1-6 1-3        2             9

数据可以根据需要重新格式化。你知道吗

编辑:原来的问题有不必要的字符串在分数,使它更容易阅读。你知道吗


Tags: 数据字符串编辑分数球员破折号playerscoreeventscore
1条回答
网友
1楼 · 发布于 2024-03-29 14:43:51

不是特别优雅,但这很有效,使用regex查找-前后的数字:

df['playerScore'] = df.eventScore.str.findall('(\d+)-').apply(pd.Series, dtype=float).sum(1)
df['opponentScore'] = df.eventScore.str.findall('-(\d+)').apply(pd.Series, dtype=float).sum(1)

>>> df
  eventScore  playerScore  opponentScore
0        5-4          5.0            4.0
1    6-2 6-0         12.0            2.0
2    6-2 6-3         12.0            5.0
3    7-6 6-2         13.0            8.0
4    2-6 4-6          6.0           12.0
5    1-6 1-3          2.0            9.0

相关问题 更多 >