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

python:获取pandas系列列表长度的有效方法[复制]

  •  0
  • muazfaiz  · 技术社区  · 6 年前

    我得到以下系列。我想计算每个国家的名单长度。

    Scotland                [1074957, 1074964, 1074968, 1074970, 287855, 3...
    South Africa            [1020029, 1031431, 1031433, 1031435, 222678, 2...
    Sri Lanka               [1001349, 1001351, 1001353, 1083449, 1083450, ...
    United Arab Emirates    [1072206, 1072207, 1072208, 1074962, 1074965, ...
    West Indies             [1041615, 1041617, 1050217, 1050219, 1050221, ...
    Zimbabwe                [1007655, 1007657, 1007659, 287856, 287858, 41...
    Name: Id, dtype: object
    

    这样产生的序列或数据帧将

    Scotland              35
    South Africa          57
    Sri Lanka             12
    United Arab Emirates  31
    West Indies           74
    Zimbabwe               9
    

    在熊猫身上,我们怎么能用蟒蛇的方式呢?

    1 回复  |  直到 6 年前
        1
  •  3
  •   jezrael    6 年前

    使用 str.len() 只有:

    a.str.len()
    

    对于 DataFrame :

    df['col'].str.len()
    

    但是如果没有 NaN S值 apply(len) 工作效率更高:

    a.apply(len)
    
    df['col'].apply(len)
    

    列出理解解决方案:

    pd.Series([len(x) for x in a], index=a.index)
    pd.Series([len(x) for x in df['col']], index=df.index)