我有一系列字符串,我正在尝试创建一个新列来计算每个字符串中大写单词的数量,约束条件是单词大于 1。例如,系列
s = pd.Series(['I AM MAD!', 'Today is a nice day', 'This restaurant SUCKS'])
Run Code Online (Sandbox Code Playgroud)
将返回值为 2、0、1 的系列。
此处的其他一些有用问题向我展示了对单个字符串执行此操作的一种方法:
sum(map(str.isupper, [word for word in s[0].split() if len(word) > 1]))
Run Code Online (Sandbox Code Playgroud)
正确返回2。
但我想知道如何将其应用于整个系列而不遍历每个元素?
您可以使用regex提取单词,然后计数:
(s.str.extractall(r'(\b[A-Z]{2,}\b)') # extract all capitalized words with len at least 2
.groupby(level=0).size() # count by each index
.reindex(s.index, fill_value=0) # fill the missing with 0
)
Run Code Online (Sandbox Code Playgroud)
输出:
0 2
1 0
2 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)