带有 lambda 的 Python pandas 应用难度 [英] Python pandas with lambda apply difficulty

查看:33
本文介绍了带有 lambda 的 Python pandas 应用难度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行以下函数,但不知何故努力让它考虑长度条件(if 部分).如果函数只运行第一部分:

I am running the following function but somehow struggling to have it take the length condition into account (the if part). It simply runs the first part if the function only:

stringDataFrame.apply(lambda x: x.str.replace(r'[^0-9]', '') if (len(x) >= 7) else x)

出于某种原因,它以某种方式只运行 x.str.replace(r'[^0-9]', '') 部分,我在这里做错了什么,我被卡住了.

it somehow only runs the x.str.replace(r'[^0-9]', '') part for some reason, what am I doing wrong here i have been stuck.

推荐答案

您可以使用 applymap 当您需要分别处理每个值时,因为 apply 适用于 all column(系列).

You can use applymap when you need to work on each value separately, because apply works with all column (Series).

然后而不是使用 str.replace,使用 re.sub 效果更好对于正则表达式:

Then instead of using str.replace, use re.sub which works nicer for regexs:

print (stringDataFrame.applymap(lambda x: re.sub(r'[^0-9]', '', x) if (len(x) >= 7) else x))

示例:

import pandas as pd
import re

stringDataFrame = pd.DataFrame({'A':['gdgdg454dgd','147ooo2', '123ss45678'],
                                'B':['gdgdg454dgd','x142', '12345678a'],
                                'C':['gdgdg454dgd','xx142', '12567dd8']})

print (stringDataFrame)
             A            B            C
0  gdgdg454dgd  gdgdg454dgd  gdgdg454dgd
1      147ooo2         x142        xx142
2   123ss45678    12345678a     12567dd8

print (stringDataFrame.applymap(lambda x: re.sub(r'[^0-9]', '', x) if (len(x) >= 7) else x))
          A         B       C
0       454       454     454
1      1472      x142   xx142
2  12345678  12345678  125678

这篇关于带有 lambda 的 Python pandas 应用难度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆