我有一个羽毛球俱乐部比赛历史记录的CSV文件。我希望能够找到有关包含给定玩家的游戏的信息(例如,“比尔”和谁玩得最多?)。这是两个三场比赛的回合示例:
import pandas as pd
player_data = player_data = pd.DataFrame(data=[
('2018-06-12', 1, 1, 1, 'Adam'),
('2018-06-12', 1, 1, 2, 'Bill'),
('2018-06-12', 1, 1, 3, 'Cindy'),
('2018-06-12', 1, 1, 4, 'Derek'),
('2018-06-12', 1, 2, 1, 'Edward'),
('2018-06-12', 1, 2, 2, 'Fred'),
('2018-06-12', 1, 2, 3, 'George'),
('2018-06-12', 1, 2, 4, 'Harry'),
('2018-06-12', 1, 3, 1, 'Ian'),
('2018-06-12', 1, 3, 2, 'Jack'),
('2018-06-12', 1, 3, 3, 'Karl'),
('2018-06-12', 1, 3, 4, 'Laura'),
('2018-06-12', 2, 1, 1, 'Karl'),
('2018-06-12', 2, 1, 2, 'Cindy'),
('2018-06-12', 2, 1, 3, 'Bill'),
('2018-06-12', 2, 1, 4, 'Derek'),
('2018-06-12', 2, 2, 1, 'Max'),
('2018-06-12', 2, 2, 2, 'George'),
('2018-06-12', 2, 2, 3, 'Fred'),
('2018-06-12', 2, 2, 4, 'Ian'),
('2018-06-12', 2, 3, 1, 'Nigel'),
('2018-06-12', 3, 3, 2, 'Edward'),
('2018-06-12', 3, 3, 3, 'Harry'),
('2018-06-12', 3, 3, 4, 'Adam')],
columns=['Date', 'Round #', 'Court #', 'Space', 'Name'])
但是,由于每一行都是单个玩家的条目,因此只需按名称即可定位,例如
player_data.loc[player_data['Name'] == 'Bill']
仅将返回Bill的各个条目,就像这样:
Date Round # Court # Space Name
1 2018-06-12 1 1 2 Bill
14 2018-06-12 2 1 3 Bill
...当我想要的是一个新的数据框,其中包含比尔玩过的游戏的所有条目时,在这种情况下,它将显示为:
Date Round # Court # Space Name
0 2018-06-12 1 1 1 Adam
1 2018-06-12 1 1 2 Bill
2 2018-06-12 1 1 3 Cindy
3 2018-06-12 1 1 4 Derek
12 2018-06-12 2 1 1 Karl
13 2018-06-12 2 1 2 Cindy
14 2018-06-12 2 1 3 Bill
15 2018-06-12 2 1 4 Derek
我认为将原始数据帧转换为一个更容易,其中每个条目都是一个单独的游戏,该游戏的所有玩家名称都列在元组中,因此检查“是否名称中的名称”?例如
Date Round # Court # Names
0 2018-06-12 1 1 (Adam, Bill, Cindy, Derek)
...但是可能会导致其他问题。
答案 0 :(得分:3)
使用merge
s1=player_data.loc[player_data['Name'] == 'Bill',['Date','Round #','Court #']]
s2=s1.merge(player_data,how='left')
s2
Out[12]:
Date Round # Court # Space Name
0 2018-06-12 1 1 1 Adam
1 2018-06-12 1 1 2 Bill
2 2018-06-12 1 1 3 Cindy
3 2018-06-12 1 1 4 Derek
4 2018-06-12 2 1 1 Karl
5 2018-06-12 2 1 2 Cindy
6 2018-06-12 2 1 3 Bill
7 2018-06-12 2 1 4 Derek
答案 1 :(得分:0)
我的方法是:
bill_player_data = player_data.loc[player_data['Name'] == 'Bill']
ro = bill_player_data['Round #']
co = bill_player_data['Court #']
bill = player_data.loc[player_data['Round #'].isin(ro)]
bill = bill.loc[bill['Court #'].isin(co)]
bill