Python:获得Pandas系列列表长度的有效方法

时间:2018-06-06 13:11:34

标签: python pandas dataframe

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

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

这样得到的系列OR Dataframe将是

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

在Pandas中,我们怎样才能以Pythonic的方式做到这一点?

1 个答案:

答案 0 :(得分:3)

仅使用str.len()

a.str.len()

对于DataFrame的列:

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

但如果没有NaN个值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)