[英]Extract second character from string in Python
I have a dataframe with a column that holds certain values where I would like to extract the second string after the hyphen and keep the original.我有一个 dataframe 列,其中包含某些值,我想在连字符之后提取第二个字符串并保留原始值。
Data数据
type stat
SSS-AA-11111 y
FFF-BB-22222 y
Desired期望的
type type1 stat
SSS-AA-11111 AA y
FFF-BB-22222 BB y
Doing正在做
df[['type', 'type1']] = df['type'].str.split('-', 1, expand=True)`
I get this error:我收到此错误:
ValueError: Columns must be same length as key
I am still researching.我还在研究。 Any suggestion is appreciated
任何建议表示赞赏
Use str.split
and keep the second element with str[1]
:使用
str.split
并使用str[1]
保留第二个元素:
df['type1'] = df['type'].str.split('-').str[1]
print(df)
# Output
type stat type1
0 SSS-AA-11111 y AA
1 FFF-BB-22222 y BB
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.