python - 字符串中的第三个字符索引
问题描述
我在 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。我想:
- “文化冲突,未来,太空战争”
- “海洋,吸毒,异国岛屿”
有人可以帮我吗?
解决方案
尝试这个,
>>> 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]
将它们连接起来,
。
推荐阅读
- terraform - 向 Terraform 脚本添加条件布尔值
- karate - 如何在空手道 API 中参数化 Cookie?
- java - 我们如何使用 gson.JsonObject 在非静态 java 方法/类中创建 Json
- java - 如何将很多位图合并为一个
- java - 通过命令行覆盖 Surefire 配置
- php - 更新:如何参数化具有“IN”子句的查询?
- c# - 如何从 XElement 对象中提取 XML 命名空间前缀?
- python-3.x - 如何从 2 个 Dataframe 中合并 2 行
- javascript - 输入字段专注于 safari
- javascript - 从 url 同步 base64 编码