【发布时间】:2018-06-29 02:34:52
【问题描述】:
说我有:
s = 'white male, 2 white females'
并希望将其“扩展”为:
'white male, white female, white female'
更完整的案例列表如下:
- '两名西班牙裔男性,两名西班牙裔女性'
- --> '西班牙裔男性,西班牙裔男性,西班牙裔女性,西班牙裔女性'
- '2 黑人男性,白人男性'
- --> '黑人男性,黑人男性,白人男性'
看来我很接近:
import re
# Do I need boundaries here?
mult = re.compile('two|2 (?P<race>[a-z]+) (?P<gender>(?:fe)?male)s')
# This works:
s = 'white male, 2 white females'
mult.sub(r'\g<race> \g<gender>, \g<race> \g<gender>', s)
# 'white male, white female, white female'
# This fails:
s = 'two hispanic males, 2 hispanic females'
mult.sub(r'\g<race> \g<gender>, \g<race> \g<gender>', s)
# ' , , hispanic males, hispanic female, hispanic female,'
在第二种情况下造成绊倒的原因是什么?
额外问题:熊猫系列有没有直接实现这个功能的方法而不是使用Series.apply()?很抱歉修改我的问题并在这里浪费任何人的时间。
例如,在:
s = pd.Series(
['white male',
'white male, white female',
'hispanic male, 2 hispanic females',
'black male, 2 white females'])
有比以下更快的路线:
s.apply(lambda x: mult.sub(..., x))
【问题讨论】:
-
Pandas 确实提供了一堆向量化的字符串函数。我的正则表达式不是最好的,因此将您的问题中的所有内容转换为它们的功能有点复杂。但是,阅读他们的文档可能会让您接近解决问题:pandas.pydata.org/pandas-docs/stable/text.html
-
是的,我很熟悉——认为它可以通过
.str.replace()@DataSwede 实现