【问题标题】:Replacing numeric value with a different numeric value用不同的数值替换数值
【发布时间】:2022-01-20 21:18:13
【问题描述】:

我在 Python 中导入了一个 CSV 文件。其中一个字段是 11 位数字。前 2 位数字都以 27 开头。如何将 27 替换为 0?

【问题讨论】:

标签: python pandas


【解决方案1】:

试试下面的代码: df['column_name']=df['column_name'].replace([original_value], new_value) 如果要替换多个值: df['column_name']=df['column_name'].replace([v1, v2, v3], [a, b, c])

【讨论】:

    【解决方案2】:

    假设您的列看起来像这样

        column_name
    0   273525235
    1   2724112414124
    2   34214124124
    

    1. astype('string') 首先将该数字列转换为 string

    2. 使用str.replace('27', '00')27 替换为00 然后

    3. astype('int64') 将再次将该字符串列转换为数字。

      data['column_name'] = data['column_name'].astype('string').str.replace('27', '00').astype('int64')
      

    输出

        column_name
    0   3525235
    1   24112414124
    2   34214124124
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多