csv 合并和删除,然后复制行

ezykj2lf  于 2023-05-04  发布在  其他
关注(0)|答案(2)|浏览(161)

我有一个关于赛马的分段时间的DF。对于每一场比赛,它都有一条名为“Race_Leader”的线路。这不是一匹真正的马,它只是比赛中领先者的数据。我想'Race_Leader'行被删除,我想它被复制,以便每个'HorseId'有相应的数据,该种族的种族领导人。请看下面的例子我想要的输出。
仅供参考,对于“Race_Leader”,“HorseId”始终= 0
df的例子:

HorseId    Name             RaceId    Sectionals
0          Race_Leader      123       41.3
224        Winx             123       42.4
225        Black Caviar     123       41.3
226        Rekindling       123       44.4
227        Fabergino        123       43.2

所需输出:

HorseId    Name             RaceId    Sectionals  RL Sectionals 
224        Winx             123       42.4           41.3
225        Black Caviar     123       41.3           41.3
226        Rekindling       123       44.4           41.3
227        Fabergino        123       43.2           41.3
2guxujil

2guxujil1#

使用掩码,既可以在ffill之后assign一个新列,又可以执行布尔索引:

m = df['Name'].eq('Race_Leader')

out = df.assign(**{'RL Sectionals': df['Sectionals'].where(m).ffill()})[~m]
  • 注意:如果您有几行“Race_Leader”,则给定行的“RL Sectionals”值将始终是前一个比赛领导者的值。

输出:

HorseId          Name  RaceId  Sectionals  RL Sectionals
1      224          Winx     123        42.4           41.3
2      225  Black Caviar     123        41.3           41.3
3      226    Rekindling     123        44.4           41.3
4      227     Fabergino     123        43.2           41.3
sczxawaw

sczxawaw2#

编码

df['RL Sectionals'] = df.groupby('RaceId')['Sectionals'].transform('min')
df[df['Name'].ne('Race_Leader')]

输出:

HorseId    Name             RaceId    Sectionals  RL Sectionals 
1    224        Winx             123       42.4           41.3
2    225        Black Caviar     123       41.3           41.3
3    226        Rekindling       123       44.4           41.3
4    227        Fabergino        123       43.2           41.3

相关问题