【问题标题】:How to replace multiple values to one in Python3如何在Python3中将多个值替换为一个
【发布时间】:2020-04-14 17:55:12
【问题描述】:

我目前正在尝试从数据框中的行中获取国家/地区。这是我目前拥有的代码:

l = [
 ['[Aydemir, Deniz\', \' Gunduz, Gokhan\', \' Asik, Nejla] Bartin 
   Univ, Fac Forestry, Dept Forest Ind Engn, TR-74100 Bartin, 
   Turkey\', \' [Wang, Alice] Lulea Univ Technol, Wood Technol, 
   Skelleftea, Sweden',1990],
 ['[Fang, Qun\', \' Cui, Hui-Wang] Zhejiang A&F Univ, Sch Engn, Linan 
   311300, Peoples R China\', \' [Du, Guan-Ben] Southwest Forestry 
   Univ, Kunming 650224, Yunnan, Peoples R China',2005],
 ['[Blumentritt, Melanie\', \' Gardner, Douglas J.\', \' Shaler 
   Stephen M.] Univ Maine, Sch Resources, Orono, ME USA\', \' [Cole, 
   Barbara J. W.] Univ Maine, Dept Chem, Orono, ME 04469 USA',2012],
 ['[Kyvelou, Pinelopi; Gardner, Leroy; Nethercot, David A.] Univ 
   London Imperial Coll Sci Technol & Med, London SW7 2AZ, 
   England',1998]]
dataf = pd.DataFrame(l, columns = ['Authors', 'Year'])

这是数据框。这是代码:

df = (dataf['Authors']
  .replace(r"\bUSA\b", "United States", regex=True)
  .apply(lambda x: geotext.GeoText(x).countries))

问题是 GeoText 无法识别“USA”,但现在我也看到需要将“England”、“Scotland”、“Wales”和“Northern Ireland”更改为“United Kingdom”。 我如何扩展.replace 来实现这一点?

【问题讨论】:

  • 尝试更好地格式化数组,这样阅读起来非常困难
  • 多个replaces? IE。 dataf['Authors'].replace(...).replace(...).apply(...)
  • @A.J.Uppal 我在想是否还有其他方法,谢谢!

标签: python python-3.x pandas gis geo


【解决方案1】:

您可以使用Series.str 模块的translate 方法并传递替换字典。

dataf.Authors.str.translate({
    'USA': 'United States', 
    "England": "United Kingdom", 
    "Scotland": "United Kingdom", 
    "Wales": "United Kingdom",
    "Northern Ireland": "United Kingdom"
})

【讨论】:

  • 我可以在最后添加.apply(lambda x: geotext.GeoText(x).countries))吗?
  • 是的,我不明白为什么不这样做。
【解决方案2】:

这对我有用。代码如下:

replace_list = ['England', 'Scotland', 'Wales', 'Northern Ireland']
for check in replace_list:
    dataf['Authors'] = dataf['Authors'].str.replace(check, 'United Kingdom', regex=True)

【讨论】:

    猜你喜欢
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    相关资源
    最近更新 更多