【问题标题】:pandas column modification with regular expression使用正则表达式修改 pandas 列
【发布时间】:2020-06-08 21:46:41
【问题描述】:

我想修复 pandas 系列中的一些字符串条目,这样所有模式为“0x.202”(缺少年份的最后一位)的值都将在末尾附加一个零(这样它就是完整的日期格式为“mm.yyyy”)。这是我得到的模式:

pattern = '\d*\.202(?:$|\W)'

精确匹配以点分隔的 2 位数字,最后精确匹配 202。能否请您帮助我如何在保留原始索引的同时替换串联字符串?

我目前的做法是:

date = df['Calendar Year/Month'].astype('str')
pattern = re.compile('\d*\.202(?:$|\W)')
date.str.replace(pattern, pattern.pattern + '0', regex=True)

但我得到一个错误:

error: bad escape \d at position 0

编辑:抱歉缺少细节,我忘了提到日期被 pandas 误解为浮点数,这就是为什么没有完全显示 2020 年的日期(例如,5.2020 舍入为 5.202)。所以我使用的表达方式:

date = df['Year/Month'].astype('str')
date = date.apply(lambda _: _ if _[-1] == '1' or _[-1] == '9' else f'{_}0')

因此只有“xx.202”被编辑,“xx.2021”和“xx.2019”等日期被省略。谢谢大家的帮助!

【问题讨论】:

  • 也许re.compile(r'\d*\.202(?:$|\W)') ?
  • 感谢您的关注,但还是同样的错误

标签: python database pandas python-re


【解决方案1】:

你必须在这里使用正则表达式吗?如果不是,这将起作用(如果字符串的长度为 x,则添加 0)。

df["Calendar Year/Month"].apply(lambda _: _ if len(_)==7 else f'{_}0')

或者这样(如果最后一位是 2,则添加 0):

df["Calendar Year/Month"].apply(lambda _: _ if _[-1] == 0 else f'{_}0')

【讨论】:

  • 嘿,感谢您的回答,不错的方法,但是例如“12.202”之类的日期也应该修改
  • 嘿,Bollo7,我添加了一种新方法,它也可以工作
  • 最后一个变种对我有用!这就是我使用的 "date = date.apply(lambda : _ if _[-1] == '1' or _[-1] == '9' else f'{}0' )”。仅向末尾不包含 9 或 1 的字符串添加零(省略 2019 和 2021)。抱歉,没有详细说明,我忘了提到日期被 pandas 误解为浮点数,这就是为什么没有完全显示 2020 年的日期(例如,5.2020 舍入为 5.202)。
  • 很高兴为您提供帮助!这种方法也应该比正则表达式更快:)
【解决方案2】:

我会做一个str.replace:

df = pd.DataFrame({'Year/Month':['10.202 abc', 'abc 1.202']})
df['Year/Month'].str.replace(r'(\d*\.202)\b', r'\g<1>0')

输出:

0    10.2020 abc
1    abc 1.2020
Name: Year/Month, dtype: object

【讨论】:

  • 嘿,您的方法适用于所有以一位数字开头的值,但是如何处理像“11.202”这样的日期呢?
猜你喜欢
  • 2013-02-07
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
相关资源
最近更新 更多