【问题标题】:How to concatenate some digits to another digit given the following constraints?给定以下约束,如何将一些数字连接到另一个数字?
【发布时间】:2017-07-10 06:40:03
【问题描述】:

我正在规范化熊猫数据框中的一些年份值。

   years

0  2011
1  2012
2  2050
3  11
4  23
5  01
 ....
n  2015

如您所见,有些值是错误的,因为它们必须是 4 位数字。因此,我想将它们转换为四位数字:

   year

0  2011
1  2012
2  2050
3  2011
4  2023
5  2001
  ...
n  2015

对于以上内容,在previous question 中我了解到您可以使用函数替换来完成此任务:

df['years'].replace('\b\d{2}\b.*?', r'20\2', regex=True)

我尝试了不同的正则表达式:

^[0-9]{2}
^[0-9]{2}.*
(\d\d)*
^(\d{2})
r'\b\d{2}\b'

但是,这些都不起作用。因此,如何用四位数字(添加20)对上述数据帧进行归一化?

【问题讨论】:

  • years 列的 dtype 是什么?
  • @MaxU year object dtype: object

标签: python regex python-3.x pandas


【解决方案1】:
df.years = pd.to_numeric(df.years, errors='coerce')

In [12]: df
Out[12]:
   years
0   2011
1   2012
2   2050
3     11
4     23
5      1
6   2015

In [13]: df.loc[df.years <= 50, 'years'] += 2000

In [14]: df
Out[14]:
   years
0   2011
1   2012
2   2050
3   2011
4   2023
5   2001
6   2015

更新:转换为字符串:

In [35]: df
Out[35]:
    years
0  2011.0
1  2012.0
2  2050.0
3  2011.0
4  2023.0
5  2001.0
6     NaN
7  2015.0

In [36]: df.dtypes
Out[36]:
years    float64
dtype: object

In [37]: df.years.where(df.years.notnull(), '')
Out[37]:
0    2011
1    2012
2    2050
3    2011
4    2023
5    2001
6
7    2015
Name: years, dtype: object

【讨论】:

  • 这个最直接,不错!
  • @tumbleweed,这意味着您有一些无法转换为数字的值,例如字符串(如'aaa')或NaN's 或日期等。
  • @tumbleweed,你的最终目标是什么?
  • df.loc[df.years
  • @tumbleweed,请参阅更新部分
【解决方案2】:

如果 years 还不是一个字符串,你可以转换它:

df['years'] = df['years'].astype(str)

现在您可以找到具有“短年份”值的条目,即年份少于四个字符的条目。将其保存为一系列 bool 以索引到数据帧中:

short_years = df['years'].str.len() < 4

最后将值修改为四个字符长:

df.loc[short_years, 'years'] = df[short_years]['years'].map(lambda yr: '2{:03d}'.format(int(yr)))

在 map 中使用 lambda 假设年份中的所有值都可以转换为 int。如果不是这种情况,您可能需要定义一个函数:

def atoi(s):
    """Convert string to integer, if possible, otherwise return None."""
    try:
        return int(s)
    except ValueError:
        return None

df.loc[short_years, 'years'] = df[short_years]['years'].map(atoi)

【讨论】:

  • 感谢汤姆的帮助
【解决方案3】:
df['years'].astype(int).apply(lambda year: 2000 + year if year < 2000 else year).astype(str)

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多