如何从Pandas数据框中的列中将列拆分为字母值和数字值? [英] How to split a column into alphabetic values and numeric values from a column in a Pandas dataframe?

查看:837
本文介绍了如何从Pandas数据框中的列中将列拆分为字母值和数字值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

    Name    Section
1   James   P3
2   Sam     2.5C
3   Billy   T35
4   Sarah   A85
5   Felix   5I

如何将数字值拆分为称为Section_Number的单独列,以及如何将字母值拆分为Section_Letter. 期望的结果

How do I split numeric values into a separate column called Section_Number and also split alphabetic values to Section_Letter. Desired results

    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

推荐答案

使用[A-Z]+ ="=" nofollow noreferrer> str.extract :

Use str.replace with str.extract by [A-Z]+ for all uppercase strings:

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

对于小写值,还可以使用

For seelct also lowercase values:

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

这篇关于如何从Pandas数据框中的列中将列拆分为字母值和数字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆