Pandas str.replace don't get anything

I run the program:

# encoding=utf-8
import pandas
df=pandas.DataFrame([['11-20','a',1],['10-20  更新于16-10-20 18:07','b',2],['15-12-27','c',3],['15-10-26  更新于10-26 23:52','d',4]],columns=['date','name','type'])
df.date=df.date.str.replace('^(\d+)(-)(\d+)((-)\d+){0,1}(.*)','\1\2\3\4')
print df

this is the result:

    date name  type
0         a     1
1         b     2
2         c     3
3         d     4

I want to get the result:

       date name  type
0     11-20    a     1
1     10-20    b     2
2  15-12-27    c     3
3  15-10-26    d     4

I also check this regex at https://regex101.com/r/apIT0O/8 . But I do not know where the problem is.

+4
source share
2 answers

You need to do literary replacement groups:

df.date.str.replace('^(\d+)(-)(\d+)((-)(\d+)){0,1}(.*)',r'\1\2\3\4')

#0       11-20
#1       10-20
#2    15-12-27
#3    15-10-26
#Name: date, dtype: object

Or you can use double backslash:

df.date.str.replace('^(\d+)(-)(\d+)((-)(\d+)){0,1}(.*)', '\\1\\2\\3\\4')

Without using a regex, you can also break into space and take the first element:

df.date.str.split(" ").str[0]

#0       11-20
#1       10-20
#2    15-12-27
#3    15-10-26
#Name: date, dtype: object
+1
source

You can simplify your regular expression.

df.date.str.replace('^(\d+-\d+)(-\d+)?.*',r'\1\2')

See the demo.

https://regex101.com/r/apIT0O/9

+1
source

Source: https://habr.com/ru/post/1664370/


All Articles