如何将列拆分为Pandas数据帧中的列的字母值和数值?
发布时间:2020-12-20 11:06:11 所属栏目:Python 来源:网络整理
导读:我有一个数据帧: Name Section1 James P32 Sam 2.5C3 Billy T354 Sarah A855 Felix 5I 如何将数值拆分为名为Section_Number的单独列,并将字母值拆分为Section_Letter. 期望的结果 Name Section Section_Number Section_Letter1 James P3 3 P2 Sam 2.5C 2.5
我有一个数据帧:
Name Section 1 James P3 2 Sam 2.5C 3 Billy T35 4 Sarah A85 5 Felix 5I 如何将数值拆分为名为Section_Number的单独列,并将字母值拆分为Section_Letter. Name Section Section_Number Section_Letter 1 James P3 3 P 2 Sam 2.5C 2.5 C 3 Billy T35 35 T 4 Sarah A85 85 A 5 Felix 5L 5 L 解决方法
对于所有大写字符串,使用
str.replace 和[A-Z]的
str.extract :
df['Section_Number'] = df['Section'].str.replace('([A-Z]+)','') df['Section_Letter'] = df['Section'].str.extract('([A-Z]+)') print (df) Name Section Section_Number Section_Letter 1 James P3 3 P 2 Sam 2.5C 2.5 C 3 Billy T35 35 T 4 Sarah A85 85 A 5 Felix 5I 5 I 对于seelct也是小写值: df['Section_Number'] = df['Section'].str.replace('([A-Za-z]+)','') df['Section_Letter'] = df['Section'].str.extract('([A-Za-z]+)') print (df) Name Section Section_Number Section_Letter 1 James P3 3 P 2 Sam 2.5C 2.5 C 3 Billy T35 35 T 4 Sarah A85 85 A 5 Felix 5I 5 I (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |