gpt4 book ai didi

python - pandas 在数据帧之间交换行

转载 作者:太空宇宙 更新时间:2023-11-03 17:23:01 25 4
gpt4 key购买 nike

我有篮球队,每个篮球队都在 pandas 数据框中。我想交易球员。玩家的顺序很重要,因此如果玩家从第二个位置出来,我希望该玩家进入同一个位置。

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

最佳答案

我的解决方案通过索引标签交换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

关于python - pandas 在数据帧之间交换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32929927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com