如何确定 pandas 数据框列中列表的长度 [英] How to determine the length of lists in a pandas dataframe column

查看:80
本文介绍了如何确定 pandas 数据框列中列表的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不用迭代如何确定列中列表的长度?

How can the length of the lists in the column be determine without iteration?

我有一个这样的数据框:

I have a dataframe like this:

                                                    CreationDate
2013-12-22 15:25:02                  [ubuntu, mac-osx, syslinux]
2009-12-14 14:29:32  [ubuntu, mod-rewrite, laconica, apache-2.2]
2013-12-22 15:42:00               [ubuntu, nat, squid, mikrotik]

我正在计算 CreationDate 列中列表的长度,并创建一个新的 Length 列,如下所示:

I am calculation length of lists in the CreationDate column and making a new Length column like this:

df['Length'] = df.CreationDate.apply(lambda x: len(x))

这给了我这个:

                                                    CreationDate  Length
2013-12-22 15:25:02                  [ubuntu, mac-osx, syslinux]       3
2009-12-14 14:29:32  [ubuntu, mod-rewrite, laconica, apache-2.2]       4
2013-12-22 15:42:00               [ubuntu, nat, squid, mikrotik]       4

有没有更pythonic的方法来做到这一点?

Is there a more pythonic way to do this?

推荐答案

您也可以将 str 访问器用于某些列表操作.在这个例子中,

You can use the str accessor for some list operations as well. In this example,

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

返回每个列表的长度.请参阅 str.len<的文档/code>.

returns the length of each list. See the docs for str.len.

df['Length'] = df['CreationDate'].str.len()
df
Out: 
                                                    CreationDate  Length
2013-12-22 15:25:02                  [ubuntu, mac-osx, syslinux]       3
2009-12-14 14:29:32  [ubuntu, mod-rewrite, laconica, apache-2.2]       4
2013-12-22 15:42:00               [ubuntu, nat, squid, mikrotik]       4

对于这些操作,vanilla Python 通常更快.熊猫虽然处理 NaN.以下是时间:

For these operations, vanilla Python is generally faster. pandas handles NaNs though. Here are timings:

ser = pd.Series([random.sample(string.ascii_letters, 
                               random.randint(1, 20)) for _ in range(10**6)])

%timeit ser.apply(lambda x: len(x))
1 loop, best of 3: 425 ms per loop

%timeit ser.str.len()
1 loop, best of 3: 248 ms per loop

%timeit [len(x) for x in ser]
10 loops, best of 3: 84 ms per loop

%timeit pd.Series([len(x) for x in ser], index=ser.index)
1 loop, best of 3: 236 ms per loop

这篇关于如何确定 pandas 数据框列中列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆