熊猫在数据帧之间交换行

2021-02-26 14:05:23 发布

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

我有篮球队,每个队都在熊猫数据框中。我想交换球员。球员的顺序很重要,所以如果一个球员从第二个位置出来,我希望他进入同一个位置。在

import pandas as pd

data = {'Name': [ 'Dwight_Howard ', 'Kobe_Bryant', 'Jameer_Nelson', 'Trevor_Ariza', 'Dirk_Nowitzki','Jordan_Hill', 'Eric_Gordon', 'Jeremy_Lin', 'Chandler_Parsons', 'Tim_Duncan'],
       'Pos': ['C','G','G','F','F','C','G','G','F','F'],
       'Value': [11, 8, 10, 15, 11,14, 7, 12, 13, 8]}


league = pd.DataFrame(data)
team1 = league[0:5:2]
team2 = league[1:6:2]

print team1
print team2
             Name Pos  Value
0  Dwight_Howard    C     11
2   Jameer_Nelson   G     10
4   Dirk_Nowitzki   F     11
           Name Pos  Value
1   Kobe_Bryant   G      8
3  Trevor_Ariza   F     15
5   Jordan_Hill   C     14

如果我用霍华德换希尔,我希望球队看起来像这样:

^{pr2}$
2条回答
网友
1楼 ·

我的解决方案通过索引标签交换df的值,玩家的名字是什么。在

import pandas as pd

data = {'Name': [ 'Dwight_Howard', 'Kobe_Bryant', 'Jameer_Nelson', 'Trevor_Ariza', 'Dirk_Nowitzki','Jordan_Hill', 'Eric_Gordon', 'Jeremy_Lin', 'Chandler_Parsons', 'Tim_Duncan'],
       'Pos': ['C','G','G','F','F','C','G','G','F','F'],
       'Value': [11, 8, 10, 15, 11,14, 7, 12, 13, 8]}
player1 = 'Dwight_Howard'
player2 = 'Jordan_Hill'

league = pd.DataFrame(data)
team1 = league[0:5:2]
team2 = league[1:6:2]
print team1
print team2
#            Name Pos  Value
#0  Dwight_Howard   C     11
#2  Jameer_Nelson   G     10
#4  Dirk_Nowitzki   F     11
#           Name Pos  Value
#1   Kobe_Bryant   G      8
#3  Trevor_Ariza   F     15
#5   Jordan_Hill   C     14

#set new columns from index and columns name
league['Nameindex'] = league['Name'] 
league['idx'] = league.index
#set index from column Nameindex
league = league.set_index('Nameindex')
#swap values of dataframes by labels
league.loc[[player1,player2],:] = league.loc[[player2,player1],:].values
#set index from original index
league = league.set_index('idx')
#remove index name
del league.index.name
team1 = league[0:5:2]
team2 = league[1:6:2]
print team1
print team2
#            Name Pos  Value
#5    Jordan_Hill   C     14
#2  Jameer_Nelson   G     10
#4  Dirk_Nowitzki   F     11
#            Name Pos  Value
#1    Kobe_Bryant   G      8
#3   Trevor_Ariza   F     15
#0  Dwight_Howard   C     11
网友
2楼 ·

感谢@jezrael的帖子。我可以将其简化为简单地从联盟中得到两名球员的指数值,然后在联盟中交换他们。因为球队只是联赛的指针,这就是所有需要做的。这是解决办法。再次感谢你的帮助。在

player1 = league[league.Name=='Dwight_Howard'].index.get_values()[0]
player2 = league[league.Name=='Jordan_Hill'].index.get_values()[0]
league.loc[[player1,player2],:] = league.loc[[player2,player1],:].values

相关问题