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

mua*_*aiz 2 python dataframe pandas

我收到以下系列。我想计算每个国家的列表长度。

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
Run Code Online (Sandbox Code Playgroud)

这样得到的系列 OR Dataframe 将是

Scotland              35
South Africa          57
Sri Lanka             12
United Arab Emirates  31
West Indies           74
Zimbabwe               9
Run Code Online (Sandbox Code Playgroud)

在 Pandas 中,我们如何以 Pythonic 方式做到这一点?

jez*_*ael 5

仅使用str.len()

a.str.len()
Run Code Online (Sandbox Code Playgroud)

对于 的列DataFrame

df['col'].str.len()
Run Code Online (Sandbox Code Playgroud)

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

a.apply(len)

df['col'].apply(len)
Run Code Online (Sandbox Code Playgroud)

列表理解解决方案:

pd.Series([len(x) for x in a], index=a.index)
pd.Series([len(x) for x in df['col']], index=df.index)
Run Code Online (Sandbox Code Playgroud)