我有篮球队,每个队都在熊猫数据框中。我想交易球员。玩家的顺序很重要,所以如果玩家离开第二个位置,我希望玩家能够进入同一个位置。
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
如果我交易霍华德为希尔,我希望这些团队看起来像这样:
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
答案 0 :(得分: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
答案 1 :(得分:0)
感谢@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