Python 字符串中的第三个字符索引
我有一个python字符串。根据这个字符串,我想编写一个函数,返回整个字符串,直到(不含)第三个逗号Python 字符串中的第三个字符索引,python,string,pandas,indexing,Python,String,Pandas,Indexing,我有一个python字符串。根据这个字符串,我想编写一个函数,返回整个字符串,直到(不含)第三个逗号 将熊猫作为pd导入 将numpy作为np导入 mystr=pd.系列(['文化冲突,未来,太空战争,太空殖民地,社会', ‘海洋、毒品滥用、异国小岛、东印度、爱情、叛徒】) def转换: 索引=0 计数=0 当计数小于3时: index=s.str.find(','索引) 计数=计数+1 指数+=1 返回s.str[0:index-1] 输出=变换(mystr) 出来 这是南。我想: “文化
将熊猫作为pd导入
将numpy作为np导入
mystr=pd.系列(['文化冲突,未来,太空战争,太空殖民地,社会',
‘海洋、毒品滥用、异国小岛、东印度、爱情、叛徒】)
def转换:
索引=0
计数=0
当计数小于3时:
index=s.str.find(','索引)
计数=计数+1
指数+=1
返回s.str[0:index-1]
输出=变换(mystr)
出来
这是南。我想:
- “文化冲突、未来、太空战”
- “海洋、毒品滥用、异国情调的岛屿”
有人能帮我吗?使用
str.split
Ex:
import pandas as pd
mystr = pd.Series(['culture clash, future, space war, space colony, society', 'ocean, drug abuse, exotic island, east india, love, traitor'])
print(mystr.str.split(",").str[:3].apply(",".join))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
>>> mystr.apply(lambda x : ",".join(x.split(',')[:3]))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
输出:
import pandas as pd
mystr = pd.Series(['culture clash, future, space war, space colony, society', 'ocean, drug abuse, exotic island, east india, love, traitor'])
print(mystr.str.split(",").str[:3].apply(",".join))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
>>> mystr.apply(lambda x : ",".join(x.split(',')[:3]))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
试试这个
>>> mystr = pd.Series(['culture clash, future, space war, space colony, society','ocean, drug abuse, exotic island, east india, love, traitor'])
输出:
import pandas as pd
mystr = pd.Series(['culture clash, future, space war, space colony, society', 'ocean, drug abuse, exotic island, east india, love, traitor'])
print(mystr.str.split(",").str[:3].apply(",".join))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
>>> mystr.apply(lambda x : ",".join(x.split(',')[:3]))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
说明:
import pandas as pd
mystr = pd.Series(['culture clash, future, space war, space colony, society', 'ocean, drug abuse, exotic island, east india, love, traitor'])
print(mystr.str.split(",").str[:3].apply(",".join))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
>>> mystr.apply(lambda x : ",".join(x.split(',')[:3]))
0 culture clash, future, space war
1 ocean, drug abuse, exotic island
dtype: object
- 按
进行拆分,并通过像,
这样的切片方式获取前三个单词,然后用[:3]
再次将它们连接起来,
str
方法在以下方面速度较慢:
pd.Series([','.join(i.split(',')[:3]) for i in mystr])
#pd.Series(','.join(i.split(',')[:3]) for i in mystr)