python - 列中除某些词外的标题词

标签 python python-3.x pandas

除了列表中的单词,我如何命名所有单词,保留?

keep = ['for', 'any', 'a', 'vs']
df.col
 ``         
0    1. The start for one
1    2. Today's world any
2    3. Today's world vs. yesterday.

预期输出:
     number   title
0     1       The Start for One
1     2       Today's World any
2     3       Today's World vs. Yesterday.


我试过
df['col'] = df.col.str.title().mask(~clean['col'].isin(keep))

最佳答案

这是处理 str.replace 的一种方法并传递替换函数:

def replace(match):
    word = match.group(1)
    if word not in keep:
        return word.title()
    return word

df['title'] = df['title'].str.replace(r'(\w+)', replace)
   number                         title
0       1             The Start for One
1       2             Today'S World any
2       3  Today'S World vs. Yesterday.

关于python - 列中除某些词外的标题词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66348567/

相关文章:

python - 两次列出过滤器对象将返回一个空白列表?

python - 将数值映射到字符串

python - 我想将数据框转换为列表列表,其中包含第一个列表中的列名和其他列表中的数据

python - 列表中字符串中间的正则表达式 (Python)

python - 从堆 : why siftup and siftdown need to be called? 中移除值

python - 检索包含 NaN 值的行的索引

python - 我在 seaborn import : 中面临这个问题

python - 将多个列表连接成一个数据结构

python - django模型版本控制包之间的比较

python-3.x - Python 调试器没有进入协程?