代码之家  ›  专栏  ›  技术社区  ›  splinter

在Pandas中寻找由列表元素组成的序列的模式

  •  2
  • splinter  · 技术社区  · 8 年前

    我和一个 pd.Series 其中每个条目都是一个列表。我想找到该系列的模式,即本系列中最常见的列表。我试过两者都用 pandas.Series.value_counts pandas.Series.mode 但是,这两种方法都会导致出现以下例外情况:

    TypeError:无法损坏的类型:“列表”

    以下是此类系列的一个简单示例:

    pd.Series([[1,2,3], [4,5,6], [1,2,3]])
    

    我正在寻找一个将返回的函数 [1,2,3]

    2 回复  |  直到 8 年前
        1
  •  5
  •   BENY    8 年前

    您需要转换为 tuple ,然后使用 mode

    pd.Series([[1,2,3], [4,5,6], [1,2,3]]).apply(tuple).mode().apply(list)
    Out[192]: 
    0    [1, 2, 3]
    dtype: object
    

    略微改善:

    list(pd.Series([[1,2,3], [4,5,6], [1,2,3]]).apply(tuple).mode().iloc[0])
    Out[210]: [1, 2, 3]
    

    因为两个应用程序很难看

    s=pd.Series([[1,2,3], [4,5,6], [1,2,3]])
    s[s.astype(str)==s.astype(str).mode()[0]].iloc[0]
    Out[205]: [1, 2, 3]
    
        2
  •  3
  •   cs95 abhishek58g    8 年前

    列表是不可散列的,因此您需要转换 Series 属于 list s到a 系列 属于 tuple s

    一旦你这样做了,你可以使用 Counter 迅速地 有效地 生成一组多元组,然后使用 Counter.most_common 提取最常见的元素(AKA mode )。

    s = pd.Series([[1,2,3], [4,5,6], [1,2,3]])
    

    from collections import Counter  
    
    c = Counter(tuple(l) for l in s)
    list(c.most_common(1)[0][0])
    [1, 2, 3]