【问题标题】:Operation on Regex identified digits in python data framepython数据框中正则表达式识别数字的操作
【发布时间】:2020-04-07 17:59:11
【问题描述】:

我有一个包含 2 列的数据框,第 3 列是下面给出的输出格式:

DF:

       reg     value   o/p**
    2 for $20    11     20/2
    4 for $24    12     24/4
    2 for $30    13     30/2
 Get $10 Cash    14     14
    3 for $30    21     30/3

首先,我必须在 reg 列中为 [$][\d]+ 匹配 [\d]+,然后 将值列更新为 reg 的第二个整数除以第一个 reg 的整数,如果没有匹配保持相同的值。

我的代码是:

df["value"]=df["reg"].map(lambda x: (int(re.findall("[\d]+",x)[1]))/int(re.findall("[\d]+",x)[0]) if(re.search(r"[\d]+ for [$][\d]+" , x)) else x)

代码输出仅对匹配情况是正确的。

【问题讨论】:

  • 问题是什么?
  • 2 for $20 中提取2 and 20 以便可以找到20/2。如果可以通过此 val 找到更改值列,否则让值保持原样。

标签: regex pandas dataframe


【解决方案1】:

试试:

df["value"]=df.apply(lambda x: (int(re.findall("[\d]+",x["reg"])[1]))/int(re.findall("[\d]+",x["reg"])[0]) if(re.search(r"[\d]+ for [$][\d]+" , x["reg"])) else x["value"], axis=1)

输出:

    reg             value
0   2 for $20       10.0
1   4 for $24       6.0
2   2 for $30       15.0
3   Get $10 Cash    14.0
4   3 for $30       10.0

您只选择 reg 列,这就是您无法获得价值的原因

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2018-09-30
    • 2015-07-31
    • 2021-04-10
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    相关资源
    最近更新 更多