如何检查字符串中的第n个字符,然后在新列中更新Python [英] How to check the n-th character in string , then update in new column Python
本文介绍了如何检查字符串中的第n个字符,然后在新列中更新Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标:如果字符串匹配条件中的字符的第8个(或第n个),则然后在新列中更新
Target : if the 8th (or n of ) of character in string match condition, then update in new column
按单词输入一个字符串:
# 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练习
Problem :
Apparently [7]
is not a python practice
在R data.table中:
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中执行此操作?
How can i do this in Python ?
推荐答案
您可以使用 np.select
此处,因为我们有多个条件:
You can use np.select
here since we have multiple conditions:
conditions = [
tt['CC'].str[7].eq('J'),
tt['CC'].str[7].eq('K'),
tt['CC'].str[7].eq('X')
]
choices = ['JANICE', 'KELVIN', 'SPECIAL']
tt['NAME'] = np.select(conditions, choices, default='NONE')
输出
CC NAME
0 T020203J71500 JANICE
1 Y020203K71500 KELVIN
2 T020407JLX100 JANICE
3 P020403JLX100 JANICE
这篇关于如何检查字符串中的第n个字符,然后在新列中更新Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文