【问题标题】:Python pandas with lambda apply difficulty具有 lambda 的 Python 熊猫应用困难
【发布时间】:2016-08-17 10:43:11
【问题描述】:

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

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

不知何故,它只运行x.str.replace(r'[^0-9]', '') 部分,我在这里做错了什么,我被卡住了。

【问题讨论】:

  • 你能举个例子说明你的问题吗?
  • x 是一个系列,len(x) 是该系列的长度。是否要检查单个字符串的长度?

标签: python pandas dataframe lambda apply


【解决方案1】:

当您需要单独处理每个值时,您可以使用applymap,因为applyall column (Series) 一起使用。

然后,不要使用str.replace,而是使用re.sub,这对正则表达式更有效:

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

【讨论】:

  • 谢谢@jezrael 这行得通。我试过 applymap 但似乎问题出在使用 str.replace
  • 只是一个快速的,也属于这个问题。当谈到 lambda 和函数时,我很可怕。但我想通过添加额外的x.contains("tel | cel | cell", case=False) 来满足两个条件。这意味着公式应该看起来像这样stringDataFrame.applymap(lambda x: re.sub(r'[^0-9]', '', x) if ((len(x) >= 7) & (x.contains("tel | cel | cell", case=False))) else x)@jezrael
  • 你需要纯python,试试print (stringDataFrame.applymap(lambda x: re.sub(r'[^0-9]', '', x) if (len(x) >= 7) and (any(ext in x.lower() for ext in ['cel','tel','cell'])) else x))
  • 感谢@jazrael,我将遍历结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多