计算 Series 中连续空格的个数

Count number of consecutive spaces in 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',
])

我想计算每个元素中连续 space 的数量。所以我的预期输出是:

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

因为第一行只包含一个连续的space,第二行包含两个连续的space(在thequick之间),第三行包含连续三个 space(在 brownfox 之间),依此类推...

我知道 ser.str.count(' '),但这会给我 space 的总数,即使它们不是连续的

您可以使用正则表达式提取所有连续的 space(使用 str.extractall), then get the lengths with str.len and find the maximum length per initial row with GroupBy.max:

(ser
 .str.extractall('(\s+)')[0]
 .str.len()
 .groupby(level=0).max()
 .reindex(ser.index, fill_value=0) # optional (see below)
)

注意。如果你有可能没有 space 的字符串并且你想得到 0,你需要 reindex.

输出:

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

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