正则表达式替换使用函数python

时间:2017-11-05 08:42:14

标签: python regex pandas

我正在尝试使用以下方式打印数据库表:

pd.read_sql_query("SELECT name,duration FROM activity where (strftime('%W', date) = strftime('%W', 'now'))", conn))

它可以打印:

                   name  duration
 0        programmation       150
 1              lecture        40
 2                  ctf        90
 3                  ceh        90
 4        deep learning       133
 5  vm capture the flag       100

但是我想使用我的函数minuteToStr将持续时间转换为duraton colowns上的字符串“1h30”。 我试过这段代码,但它不起作用:

tableau = str(pd.read_sql_query("SELECT name,duration FROM activity\
                 where (strftime('%W', date) = strftime('%W', 'now'))", conn))  
tableau = re.sub("([0-9]{2,})",   minuteToStr(int("\\1")), tableau)
print(tableau)

由于

3 个答案:

答案 0 :(得分:3)

使这很简单,只需使用一点mathemagic和字符串格式。

h = df.duration // 60
m = df.duration % 60

df['duration'] = h.astype(str) + 'h' + m.astype(str) + 'm'
df

                  name duration
0        programmation    2h30m
1              lecture    0h40m
2                  ctf    1h30m
3                  ceh    1h30m
4        deep learning    2h13m
5  vm capture the flag    1h40m

答案 1 :(得分:2)

<ul> <li><a href="#">Strona główna</a></li> <li><a href="#">O Nas</a></li> <li><a href="#">Historia</a></li> <li><a href="#">Dokumenty</a></li> <li><a href="#">Galeria</a></li> <li><a href="#">Kontakt</a></li> </ul> 无法正常工作。它需要一个字符串,而不是DataFrame。

鉴于@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) 接受整数,您只需使用apply

re.sub

答案 2 :(得分:2)

与在pandas中使用re.sub内的函数类似,我们可以使用str.replace。类似的类型使用here,即

如果duration列是整数类型,那么

tableau['duration'].astype(str).str.replace("([0-9]{2,})", minuteToStr)

否则:

tableau['duration'].str.replace("([0-9]{2,})", minuteToStr)

说明使用内部替换功能(我更喜欢你使用@ colspeed的解决方案)

def minuteToStr(x):
    h = int(x.group(1)) // 60
    m = int(x.group(1)) % 60
    return str(h) + 'h' + str(m)


df['duration'].astype(str).str.replace("([0-9]{2,})",minuteToStr)
            name duration
0     programmation     2h30
1           lecture     0h40
2               ctf     1h30
3               ceh     1h30
4      deeplearning     2h13
5  vmcapturetheflag     1h40