在系列中计算连续空格的数量

3

我有一个像这样的 Series:

import pandas as pd

ser = pd.Series([
    'the quick brown fox',
    'the  quick pink fox',
    'a quick brown   fox',
    'the jumpy  brown fox    ',
    'the quick  brown animal',
])

我想计算每个元素中连续空格的数量。所以我的期望输出是:
0    1
1    2
2    3
3    4
4    2
dtype: int64

因为第一行只包含一个连续的空格,第二行包含两个连续的空格(thequick之间),第三行包含三个连续的空格(brownfox之间),以此类推...
我知道可以用ser.str.count(' ')来获取总空格数,但即使它们不是连续的,这也会将它们计算在内。
2个回答

5
你可以使用正则表达式(使用str.extractall函数)来提取所有连续的空格,然后使用str.len函数获取长度,并使用GroupBy.max函数找到每个起始行的最大长度:
(ser
 .str.extractall('(\s+)')[0]
 .str.len()
 .groupby(level=0).max()
 .reindex(ser.index, fill_value=0) # optional (see below)
)

NB. 如果存在没有空格的字符串,并且您希望获得0,则需要使用reindex方法。

0    1
1    2
2    3
3    4
4    2
Name: 0, dtype: int64

2

findall 函数可以得到一个空格字符串的列表,只需获取每个列表中最长字符串的长度即可:

ser.str.findall(' +').apply(lambda s: max(map(len, s)) if s else 0)

结果:

0    1
1    2
2    3
3    4
4    2
dtype: int64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接