![](/img/trans.png)
[英]Pandas if colum contains string then get unique value from another column and drop rows from dataframe
[英]Get the last rows for a unique value in a column from a dataframe - Pandas
我有一个数据帧df
的摘录如下:
Player Trial Score
0 Josh 1 1
1 Josh 2 3
2 Josh 3 2
3 Josh 4 2
4 Josh 5 2
5 Josh 6 5
6 Josh 7 2
0 Yuli 1 1
1 Yuli 2 3
2 Yuli 3 2
3 Yuli 4 2
4 Yuli 5 2
0 Max 1 4
1 Max 2 6
2 Max 3 10
3 Max 4 10
4 Max 5 17
5 Max 6 10
6 Max 7 14
我想选择对“玩家”列具有唯一值的最后一行,即
Player Trial Score
0 Max 1 4
1 Max 2 6
2 Max 3 10
3 Max 4 10
4 Max 5 17
5 Max 6 10
6 Max 7 14
我试过df.groupby("Player").tail()
但这只返回每个玩家的最后 5 行。 我也尝试了一个相当冗长的方法:
df.groupby('Trial').tail().loc[df['Player'] == df['Player'].unique()[-1]]
这给了我我想要的东西,但我确定我缺少一种更清洁的方法。 任何帮助将不胜感激,以实现这一目标。 谢谢你。
如果我理解正确,您只想获取最终玩家的所有行(即玩家列中df
最后一行的名称。
last_player = df.Player.iloc[-1]
df.loc[df.Player==last_player]
打印:
Player Trial Score
7 Max 1 4
8 Max 2 6
9 Max 3 10
10 Max 4 10
11 Max 5 17
12 Max 6 10
13 Max 7 14
请注意,以不同的方式对df
进行排序很可能会改变上述代码的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.