【问题标题】:How to replace only single numbers with another number in a pandas dataframe?如何在熊猫数据框中仅用另一个数字替换单个数字?
【发布时间】:2017-07-10 01:32:31
【问题描述】:

我有以下熊猫数据框:

   date
0   1
1   2
2   23
3   31
4   4
...
n    3

我如何仅将 1 到 9 的所有数字(例如一位数字)替换为以下格式:

01, 02, 03, 04, 05, 06, 07, 08, 09

我尝试用 pandas 替换功能如下:

df['date'] = df['date'].replace(['1', '2', '3', '4', '5', '6', '7', '8', '9']),
                                                          [' 01 ', ' 02 ', ' 03 ', '04 ', ' 05 ', ' 06 ', ' 07 ', ' 08 ', ' 09 '],regex=True)

但是,它不起作用,因为它正在修改 all(即多于一位的数字)数据框中的数字。因此,如何规范化日期列?

【问题讨论】:

    标签: python regex python-3.x pandas


    【解决方案1】:

    尝试^([0-9])$ 用于模式,0\1 用于替换:

    >>> df = p.DataFrame(data={'date': ['1', '2', '12', '31']})
    >>> df['date'].replace('^([0-9])$', r'0\1', regex=True)
    
    0    01
    1    02
    2    12
    3    31
    Name: date, dtype: object
    

    阅读您在其他问题上写的 cmets,您似乎在进行日期格式化。我相信最好使用datetime。这是一个例子:

    >>> from datetime import datetime
    >>> df = p.DataFrame(data={'date': ['1', '2', '12', '31'], 'month': ['1', '2', '5', '12'], 'year': ['07', '10', '16', '17']})
    >>> dates = df.apply(lambda row: datetime(year=2000+int(row['year']), month=int(row['month']), day=int(row['date'])), axis=1)
    >>> dates
    
    0   2007-01-01
    1   2010-02-02
    2   2016-05-12
    3   2017-12-31
    dtype: datetime64[ns]
    >>> dates.apply(lambda row: row.strftime('%x'))
    
    0    01/01/07
    1    02/02/10
    2    05/12/16
    3    12/31/17
    dtype: object
    >>> dates.apply(lambda row: row.strftime('%Y-%m-%d'))
    
    0    2007-01-01
    1    2010-02-02
    2    2016-05-12
    3    2017-12-31
    dtype: object
    

    这样,您可以更好地控制日期格式。

    编辑

    如果您需要对转换进行更多控制,请改为创建一个函数:

    >>> def convert_dates(row):
    ...     year = row['year']
    ...     month = row['month']
    ...     day = row['date']
    ...     if '' in [year, month, day]:
    ...         return None # Don't bother with empty values 
    ...     year, month, day = [int(x) for x in [year, month, day]]
    ...     if year < 100:
    ...         year += 2000
    ...     return datetime(year, month, day)
    ... 
    >>> df = p.DataFrame(data={'date': ['11', '2', '1', '31'], 'month': ['08', '2', '5', '12'], 'year': ['1985', '10', '16', '']})
    >>> df.apply(convert_dates, axis=1)
    
    0   1985-08-11
    1   2010-02-02
    2   2016-05-01
    3          NaT
    dtype: datetime64[ns]
    

    【讨论】:

    • 在熊猫数据框中?
    • 是的,就像您的代码一样,但模式不同。我添加了一个示例。
    • 我用如何使用apply 创建一个实际的datetime 对象来更新这个答案,以便于格式化。
    • 听起来你的数据有点乱。我会尝试在源头而不是熊猫中修复数据。您可以编写一个更复杂的函数并使用 apply 代替该函数。
    • 正则表达式可能有效,但最终过于复杂。在这个答案中查看我的更新。
    【解决方案2】:

    使用单词边界:

    查找:\b(\d)\b
    替换:0$1

    【讨论】:

      【解决方案3】:

      如果需要,使用 astype(str) 将列转换为 str,然后调用 str.zfill 以 0 填充这些数字:

      In [13]:
      df['date'] = df['date'].astype(str).str.zfill(2)
      df
      
      Out[13]:
        date
      0   01
      1   02
      2   23
      3   31
      4   04
      

      关于您的评论:

      In [17]:
      df['year'] = '20' + df['date']
      df
      
      Out[17]:
        date  year
      0   01  2001
      1   02  2002
      2   23  2023
      3   31  2031
      4   04  2004
      

      当列 dtype 已经是 str 时,上述方法有效

      【讨论】:

      • 谢谢,我不知道这是可能的......这个解决方案很好。但是,如果我多年来一直有同样的问题怎么办?例如,考虑一列年份为 23、12、15 等。然后我需要在数字的左侧估算 20……我该怎么做?。
      • 如果已经是 str 那么你可以只做 '20' + df['year'] 或 '20' + df['year'].astype(str)
      • 你能提供例子吗?...谢谢你的帮助!
      • 好吧,我忘了提到 pandas 数据框的所有某些实例都具有正确的年份格式(例如 2011 年),当我应用字符串连接时,我会通过重新格式化为 202011 来混淆像 2011 年这样的实例。如何我可以将它应用于只有两位数的实例吗? @edchum
      • 抱歉忙于家庭事务,回答你的问题我认为df['year'] = np.where(df['date'].str.len() == 4, '20' + df['date']) 应该可以工作
      【解决方案4】:

      使用正则表达式,例如

      p = re.compile(r'\b\d\b')
      p.sub(lambda x: '0'+x.group(), '0 1 2 23 34 5')
      ## result: '00 01 02 23 34 05'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-21
        • 2023-04-03
        • 2019-06-30
        • 2018-03-25
        • 2020-07-31
        • 2020-11-15
        • 1970-01-01
        • 2015-01-19
        相关资源
        最近更新 更多