我有一個如下所示的熊貓 df,其中列出了兩名球員的分數。我想計算每場比賽連續得分的每個球員每場比賽的總和。例如 A 玩的第一局總分是 12,A 玩的第二局總分是 10,B 玩的第一局總分是 4 等等。我該怎么做熊貓方式(矢量化或 groupby 等)好嗎?
df_players.groupby("Player").sum("Score")
只給出總分,而不是單獨給出每場比賽的總分。
非常感謝。
| 播放器 | 分數 |
|---|---|
| 一個 | 10 |
| 一個 | 2 |
| 乙 | 1 |
| 乙 | 3 |
| 一個 | 3 |
| 一個 | 7 |
| 乙 | 2 |
uj5u.com熱心網友回復:
這是一個孤島和差距問題。每當玩家改變時,就會形成一個新的島嶼。
# Build the islands. If the current row's Player is not equal to the previous
# row's Player, create a new island. We don't care about the island number, only
# that rows with consecutive Player are assigned to the same island.
island = df["Player"].ne(df["Player"].shift()).cumsum().rename("Island")
result = (
# One Player one Island = one Game
df.groupby([df["Player"], island]).sum()
# Now, for each Player, label the Games consecutively
.assign(Game=lambda x: x.groupby("Player").cumcount() 1)
.set_index("Game", append=True)
)
結果:
Score
Player Island Game
A 1 1 12
3 2 10
B 2 1 4
4 2 2
uj5u.com熱心網友回復:
您的 DataFrame 中沒有 Game ...我假設您表中的前兩個分數是針對 Game #1 中的玩家 A 的,但我只是猜測,因為您說您希望結果為 12。沒有從您提供的資料中找出這一點的方法。將 Game 的列添加到 DataFrame 中,然后按玩家和游戲分組... groupby() 的 by= 引數可以獲取要分組的列串列。
uj5u.com熱心網友回復:
我想你想要cumsum().cumulative_sum
df_players.groupby('Player').cumsum()
您可以將其作為新列添加到現有框架中,例如:
df_players['Running Score'] = df_players.groupby('Player').cumsum()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/518596.html
標籤:Python熊猫
下一篇:如何對嵌套字典進行子集化
