pandas Python:按条件删除 Dataframe 中的行

vltsax25  于 2022-11-27  发布在  Python
关注(0)|答案(1)|浏览(294)

我想删除ratings df中的所有行,其中球队没有比赛。所以不要在HomeTeamAwayTeam中的fixtures df中发生。我尝试了以下操作:

fixtures = pd.DataFrame({'HomeTeam': ["Team1", "Team3", "Team5", "Team6"], 'AwayTeam': [
    "Team2", "Team4", "Team6", "Team8"]})

ratings = pd.DataFrame({'team': ["Team1", "Team2", "Team3", "Team4", "Team5",
                                 "Team6", "Team7", "Team8", "Team9", "Team10", "Team11", "Team12"], "rating": ["1,5", "0,2", "0,5", "2", "3", "4,8", "0,9", "-0,4", "-0,6", "1,5", "0,2", "0,5"]})

ratings = ratings[(ratings.team != fixtures.HomeTeam) &
                  (ratings.team != fixtures.AwayTeam)]

但我收到错误消息:

ValueError: Can only compare identically-labeled Series objects

我可以做些什么来阻止错误发生?

mftmpeh8

mftmpeh81#

因为两个 Dataframe 的大小不相等。您可以改用**isin()**。

ratings = ratings[~ratings.team.isin(fixtures.stack())]

#output
'''
    team    rating
6   Team7   0,9
8   Team9   -0,6
9   Team10  1,5
10  Team11  0,2
11  Team12  0,5

'''

详细信息:

print(fixtures.stack())
'''
0  HomeTeam    Team1
   AwayTeam    Team2
1  HomeTeam    Team3
   AwayTeam    Team4
2  HomeTeam    Team5
   AwayTeam    Team6
3  HomeTeam    Team6
   AwayTeam    Team8
dtype: object
'''

如您所见,这将返回所有值 在isin函数中使用**~**操作符,我们过滤掉那些不包含这些值的函数。

相关问题