Pandas数据框列中计算列表长度的Python方法

2024-03-28 11:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据框:

                                                    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列,如下所示:

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

有没有比这更像Python的方法?


Tags: 数据moddfubuntumacapachenatlength
1条回答
网友
1楼 · 发布于 2024-03-28 11:19:45

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

df['CreationDate'].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通常更快。但是熊猫会处理南斯。以下是时间安排:

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

相关问题 更多 >