Python:获取Pandas系列清单长度的有效方法 [英] Python: Efficient way to get the length of lists for a Pandas Series
本文介绍了Python:获取Pandas系列清单长度的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在获得以下系列。我想计算每个国家/地区的列表长度。
I am getting the following series. I want to calculate the length of list for each country.
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
在熊猫市,我们该怎么做
In Pandas how can we do this in a Pythonic way?
推荐答案
使用仅 str.len()
:
a.str.len()
对于 DataFrame
的列:
df['col'].str.len()
但是,如果没有 NaN
s的值 apply(len)
工作效率更高:
But if no NaN
s values apply(len)
working more efficient:
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)
这篇关于Python:获取Pandas系列清单长度的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文