【问题标题】:Abstract value in a csv cell using Regex in python在 python 中使用正则表达式的 csv 单元格中的抽象值
【发布时间】:2019-04-29 21:02:18
【问题描述】:

我正在从 csv 列中提取一个数值,例如:

column=[None, you earn 5%] 

如果它可以将 'None' 存储为 0,而将 5% 存储为第二个,那就太好了。

我尝试使用以下代码传输 %。但它会引发错误

"TypeError: 预期的字符串或类似字节的对象"

data.loc[(data['column'] == re.findall(r'([\w]+)', data['column'])), 'disc'] = re.findall(r'([0-9]+\%)',data['column'])

还有 for 循环。但似乎没有帮助

def fs(a):
    for i in a:
        if i == 'None':
            a[i] = 0
        else:
            a[i]=re.search(r'(?<=\().+?(?=\))', a[i])

【问题讨论】:

    标签: python regex csv


    【解决方案1】:

    如果您有一个包含字符串列的数据框,并且您想将字符串“None”替换为 0 并保留数字和 %,那么请执行以下操作:

    df.textColumn.str.replace("None","0").str.replace("[^0-9.%]", "")
    

    例子:

    import pandas as pd
    
    df = pd.DataFrame({'n':[1,2,3,4], 'text':["None","you earn 5%", "this is 3.4%", "5.5"]})
    
    df['text'] = df.text.str.replace("None","0").str.replace("[^0-9.%]", "")
    
    df
    
    n   text
    0   1   0
    1   2   5%
    2   3   3.4%
    3   4   5.5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 2018-05-10
      • 1970-01-01
      相关资源
      最近更新 更多