Pandas结构更换一无所获

2024-03-29 09:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我运行一个程序:

# 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

结果如下:

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

我想得到结果:

       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

我还检查了https://regex101.com/r/apIT0O/8上的正则表达式。但我不知道问题出在哪里


Tags: columnsnamehttpsimport程序dataframepandasdf
2条回答

你可以简化你的正则表达式。你知道吗

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

请参见演示。你知道吗

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

您需要将替换组设置为文字:

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

或者可以使用双反斜杠:

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

不使用regex,也可以在空白处拆分并获取第一个元素:

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

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

相关问题 更多 >