You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame单元格为数组时如何对每个子数组排序并实现同手牌分组

对hand列逐行排序的实现方法

你之前用lambda失败大概率是调用了原地修改的sort()方法,该方法返回None,改用返回新排序列表的sorted()函数即可:

import pandas as pd

df = pd.DataFrame({'player': ['Bob', 'Jane', 'Alice'], 
                   'hand': [['two','ace'], ['queen','king'], ['three','five']]})

# 生成排序后的手牌列
df['sorted_hand'] = df['hand'].apply(lambda x: sorted(x))

直接分组识别同手牌玩家的方案

如果你的最终需求是把不考虑顺序、手牌完全一致的玩家归为一组,不需要额外生成排序列,直接将手牌转为可哈希的排序后元组作为分组键即可(列表本身不可哈希,无法直接作为groupby的键):

# 统计每组相同手牌的玩家列表
same_hand_group = df.groupby(
    df['hand'].apply(lambda x: tuple(sorted(x)))
)['player'].apply(list).reset_index(name='same_hand_players')

# 如果只需要统计每组玩家数量,改用如下写法
same_hand_count = df.groupby(
    df['hand'].apply(lambda x: tuple(sorted(x)))
).size().reset_index(name='player_count')

内容的提问来源于stack exchange,提问作者user2759838

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:15:05