Skip to main content
 首页 » 编程设计

python之如何检查字符串中的第 n 个字符,然后在新列 Python 中更新

2025年05月04日22duanxz

目标:如果字符串中的第8(或第n)字符匹配条件,则在新列中更新

按单个字符串中的单词:

# if i want to check the 3rd character 
IN[0]:  s = "apple" 
        s[2] 
OUT[0]: 'p' 

代码:

tt = pd.DataFrame({"CC":["T020203J71500","Y020203K71500","T020407JLX100","P020403JLX100"]) 
 
tt["NAME"] = pd.np.where(tt["CC"][7].str.contains("J"),"JANICE", 
               pd.np.where(tt["CC"][7].str.contains("K"),"KELVIN", 
               pd.np.where(tt["CC"][7].str.contains("X"),"SPECIAL","NONE"))) 

问题: 显然 [7]不是python的做法

在 R 数据表中:

tt[grepl("J",str_sub(CC,8,8)), 
      "NAME":="JANICE"] 
tt[grepl("K",str_sub(CC,8,8)), 
      "NAME":="KELVIN"] # .... can achieve by doing like this  

我如何在 Python 中执行此操作?

请您参考如下方法:

使用series.str得到你正在寻找的切片 map用你的字典:

d={'J':'JANICE','K':'KELVIN','X':'SPECIAL'} 
tt['Name']=tt['CC'].str[7].map(d).fillna('NONE') 
print(tt) 

              CC    Name 
0  T020203J71500  JANICE 
1  Y020203K71500  KELVIN 
2  T020407JLX100  JANICE 
3  P020403JLX100  JANICE