Home > Back-end >  Pandas - Separating Section Number from Text
Pandas - Separating Section Number from Text

Time:12-19

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?

CodePudding user response:

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
  • Related