我在某栏中有一个信用卡到期日期的DF(格式= mm / yy) 我希望获得的卡将以mm / 25(年= 2025)到期
我正在尝试使用正则表达式来过滤该系列,但是它出了错
我测试了一些正则表达式以了解正在过滤的内容,我明白了
df.Exp_Date.filter(regex='.+') --> recognize all dates
df.Exp_Date.filter(regex='.+\/') --> return empty list
df.Exp_Date.filter(regex='.+\/.+') --> return empty list
df.Exp_Date.filter(regex='\w+') --> recognize all dates (ok)
df.Exp_Date.filter(regex='\w+\/') --> return empty list
df.Exp_Date.filter(regex='\w+\/\w+') --> return empty list
我的问题可能在/ char上。我在regexpal上测试了所有正则表达式及其在这里的工作,但未在我的过滤器上进行测试。
答案 0 :(得分:1)
尝试像这样使正则表达式字符串成为原始字符串: regex = r'。+ /。+',而不是regex ='。+ /。+'
使用原始字符串的原因是,当您使用转义字符(反斜杠)时,python与正则表达式的解释方式不同。使用原始字符串可以防止这种情况。
这里有一个更好的解释: What exactly is a "raw string regex" and how can you use it?
答案 1 :(得分:0)
您可以改用contains吗?
df1
#Out[472]:
# Name Date OPP Result
#0 Will 11/20 @DAL L110-102
#1 Bill 11/25 @POR W114-106
#2 Bill 11/24 @LAC L98-88
#3 Mark 11/25 @LAL W113-104
#4 Sam 11/25 @NO W122-104
#5 Dude 9/24 vsSAC W124-120
#6 What 8/23 @MIL L115-105
df1[df1.Date.str.contains('/25')]
#Out[473]:
# Name Date OPP Result
#1 Bill 11/25 @POR W114-106
#3 Mark 11/25 @LAL W113-104
#4 Sam 11/25 @NO W122-104