繁体   English   中英

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

[英]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',
])

我想计算每个元素中连续空格的数量。 所以我预期的 output 是:

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

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

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

您可以使用正则表达式(使用str.extractall )提取所有连续的空格,然后使用GroupBy.max获取长度并使用str.len找到每个初始行的最大长度:

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

注意。 如果您有可能没有空格的字符串并且您想获得 0,则需要重新reindex

output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM