為了說明我的問題,請考慮以下 Pandas DataFrame:
df = pd.DataFrame({'player': ['Bob', 'Jane', 'Alice'],
'hand': [['two','ace'], ['queen','king'], ['three','five']]})
我想對每個手陣列進行排序。我試過使用 lamdas 或使用 iterrow 通過 df 回圈,但我無法正常作業。
獎勵:我希望對它進行排序的原因是我可以在該列上進行分組以識別所有擁有相同手牌的玩家。也許,有一種更直接的方式來做到這一點。
uj5u.com熱心網友回復:
我會做的explode,對于你的下一步,你可以只groupby手agg玩家
df.explode('hand').groupby('hand').player.agg(list)
hand
ace [Bob]
five [Alice]
king [Jane]
queen [Jane]
three [Alice]
two [Bob]
Name: player, dtype: object
uj5u.com熱心網友回復:
你可以apply(sorted):
df['hand'] = df['hand'].apply(sorted)
輸出:
player hand
0 Bob [ace, two]
1 Jane [king, queen]
2 Alice [five, three]
這將不允許您分組,因為串列不可散列。
如果您的目標是分組或比較,并且卡片是唯一的,您還可以使用frozenset:
df['hand'] = df['hand'].apply(frozenset)
或者,如果您想考慮重復的卡片(例如,ace ace),請排序并轉換為元組:
df['hand'] = df['hand'].apply(lambda x: tuple(sorted(x)))
輸出:
player hand
0 Bob (two, ace)
1 Jane (king, queen)
2 Alice (three, five)
然后你可以groupby手牌列出同手牌的玩家:
df.groupby('hand')['player'].apply(list)
輸出:
hand
(ace, two) [Bob]
(five, three) [Alice]
(king, queen) [Jane]
Name: player, dtype: object
uj5u.com熱心網友回復:
我認為使用sorted是最好的選擇之一,在這個問題中也提出了。
>>> df['hand'] = [tuple(sorted(x)) for x in df['hand']]
>>> df
player hand
0 Bob (ace, two)
1 Jane (king, queen)
2 Alice (five, three)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371453.html
上一篇:計算與文本的時差
