Slicing strings in a data frame

Viewed 76

I have a data frame that looks like this (before).

BEFORE:
string
Oct 05 
190103  

How can I make it look like this (after)?

AFTER:
string                                  the_date
Oct 05                                  181005
190103                                  190103
3 Answers

You can use a regular expression to match the last continuous sequence of numbers between the last space of a string and the last period of a string. Use:

\s[^\s]+?(\d+)\.[^\.]+?$

str.extract

df['string'].str.extract(r'\s[^\s]+?(\d+)\.[^\.]+?$')

        0
0  181004
1  181004
2  181004
3  181106
4  181106
5  190102
6  190103
7   51811

As has been noted in the comments your last line should be 51811, or else you are not using a consistent rule throughout your DataFrame.


Regex Explanation

\s                    # match a whitespace character
[^\s]+?               # match a non whitespace character between 1 and unlimited times, lazy
(                     # start of matching group 1
  \d+                 # match 1 or more digits          
)         
\.                    # match a period character
[^\.]+?               # match a non period character one to unlimited times, lazy
$                     # assert position at end of line

You can use regular expression like this one: https://stackoverflow.com/a/54119901/9962315

or use code below, it also works fine with your data.

strToCheck = '10 30067    10224     1613788 Nov 07 01:55 USE4D181106.XBET'
the_date = ''

# step 1 - get the last substring with 'the_date' parameter
test = strToCheck.split(' ')[-1].split('.')[0]

# step 2 - loop test string and build right 'the_date' parameter 
for char in reversed(test):
    try:
        int(char)
        the_date = char+the_date
    except ValueError:
        break
print(the_date)

A simple regex seems to work well:

/[A-Z]\d(\d+)\./

It will also take care of case where CAE51811 should output 1811 but not 51811.

Related