【问题标题】:Forloop + regex works to find and replace numerics but not bracket in dataframe columnForloop + regex 用于查找和替换数字,但不能在数据框列中查找和替换括号
【发布时间】:2019-05-03 11:24:44
【问题描述】:

我在 python 中有一个数据框“energy”,其中包含国家列表的“Country”列。我正在尝试消除数字,例如,瑞士 17 到瑞士以及括号,例如,玻利维亚(.. 到玻利维亚。

我为瑞士17等数字案例工作的代码,但不适用于括号:

for cty in energy['Country']:
    try:
        y = re.findall('[0-9]',cty)[0]
        energy['Country'] = energy['Country'].str.replace(cty,cty[:cty.find(str(y))])
    except:
        continue

上面的方法有效,但下面的方法无效:

for c in energy['Country']:
    try:
        z = re.search('[(]',c)[0]
        energy['Country'] = energy['Country'].str.replace(c,c[:c.find(str(z))])
    except:
        continue

我还看到单独的 print(c,c[:c.find(str(z))]) 有效,但在 for 循环中无效。查找和替换支架哪里出错了?

【问题讨论】:

    标签: python regex dataframe


    【解决方案1】:

    使用str.replace & str.strip

    例如:

    import pandas as pd
    
    df = pd.DataFrame({'Country': ["Switzerland17", "Bolivia (KK)", "China"]})
    df["Country"] = df["Country"].str.strip("0123456789").str.replace(r"(\(.*?\))", "").str.strip()
    print(df)
    

    输出:

           Country
    0  Switzerland
    1      Bolivia
    2        China
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多