J'ai un bloc de données qui ressemble à ceci (avant).
AFTER: string the_date Oct 05 181005 190103 190103
Comment puis-je le faire ressembler à ceci (après)?
BEFORE: string Oct 05 190103
3 Réponses :
Une simple expression régulière semble bien fonctionner:
/[A-Z]\d(\d+)\./
Elle prendra également en charge le cas où CAE51811 devrait afficher 1811 mais pas 51811.
Vous pouvez utiliser une expression régulière pour faire correspondre la dernière séquence continue de nombres entre le dernier espace d'une chaîne et le dernier point d'une chaîne. Utilisez:
\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
str.extract 0 0 181004 1 181004 2 181004 3 181106 4 181106 5 190102 6 190103 7 51811
df['string'].str.extract(r'\s[^\s]+?(\d+)\.[^\.]+?$')
Vous pouvez utiliser une expression régulière comme celle-ci: https://stackoverflow.com/a/54119901/9962315 ou utilisez le code ci-dessous, cela fonctionne également très bien avec vos données.
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)
base sur votre description pourquoi la dernière ligne est 1811 et non 51811