Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas – Separating Section Number from Text

I have a column in a pandas data frame with the following format:

ColumnA
========
4 Requirements
Requirement blah blah
Requirement blah blah blah
4.1.1 Requirement Subsection
4.1.1.1 Requirement subsection subsection
blah blah blah
...

I am trying to separate the numbers from text. In other words, I would like two columns like the following:

ColA      ColB
=================================
4         Requirements
          Requirement blah blah
          Requirement blah blah blah
4.1.1     Requirement Subsection
4.1.1.1   Requirement subsection subsection
          blah blah blah
...

The section number will always be at the beginning of the record if it exists. How can I accomplish something like this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use str.extract:

df['ColumnA'].str.extract('^(\d+[.\d]*)?\s*(.*)')

# or with named capturing groups
df['ColumnA'].str.extract('^(?P<ColA>\d+[.\d]*)?\s*(?P<ColB>.*)')

Output:

      ColA                               ColB
0        4                       Requirements
1      NaN              Requirement blah blah
2      NaN         Requirement blah blah blah
3    4.1.1             Requirement Subsection
4  4.1.1.1  Requirement subsection subsection
5      NaN                     blah blah blah
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading