首页 > 解决方案 > 字符串中的第三个字符索引

问题描述

我在 python 中有一个字符串。从这个字符串中,我想编写一个函数,它返回整个字符串,直到(没有)第三个逗号。

import pandas as pd
import numpy as np

mystr = pd.Series(['culture clash, future, space war, space colony, society', 
'ocean, drug abuse, exotic island, east india, love, traitor])

def transform(s):
    index = 0
    count = 0
    while count < 3:
        index = s.str.find(',', index)        
        count = count+1
        index += 1
    return s.str[0:index-1]

out = transform(mystr)
out

这将返回 NaN。我想:

有人可以帮我吗?

标签: pythonstringpandasindexing

解决方案


尝试这个,

>>> mystr = pd.Series(['culture clash, future, space war, space colony, society','ocean, drug abuse, exotic island, east india, love, traitor'])

输出:

>>> mystr.apply(lambda x : ",".join(x.split(',')[:3]))

0    culture clash, future, space war
1    ocean, drug abuse, exotic island
dtype: object

解释:

  • 通过切片来拆分,并取前三个单词,然后再用 .[:3]将它们连接起来,

推荐阅读