【问题标题】:Replace string character in np.array替换 np.array 中的字符串字符
【发布时间】:2021-05-31 09:09:13
【问题描述】:

我有一个 numpy 数组大小 (8634,3),其中包含英语和德语混合类型的数值,例如。 34,12 和 34.15 X = np.array(df[['column_a','column_b','column_c']]) X.shape (8634,3) X.dtype dtype('O')

我想将“,”替换为“。”使用此功能:

int_X = X.replace(',','.')

但我收到此错误:

AttributeError: 'numpy.ndarray' object has no attribute 'replace'

有人可以帮助我使用我需要使用的正确功能吗?谢谢

【问题讨论】:

    标签: python pandas dataframe replace type-conversion


    【解决方案1】:

    .replace() 是一个字符串方法,所以它不能直接作用于 numpy 数组。您可以定义一个函数来对输入字符串执行此操作,然后将该函数向量化以直接将其应用于数组的所有元素。

    看看下面的示例代码sn-p。我已经将数组转换为 str 类型,完成了所需的替换,然后将它们转换回浮点数。

    import numpy as np
    
    a = np.array([1.2, 3.4, "4,5", "8,3", 6.9])
    a = a.astype(str)
    replace_func = np.vectorize(lambda x: float(x.replace(',','.')))
    a = replace_func(a)
    print(a)
    
    # Out: [1.2 3.4 4.5 8.3 6.9]
    

    使用np.char.replace()的替代方法:

    import numpy as np
    
    a = np.array([1.2, 3.4, "4,5", "8,3", 6.9])
    a = a.astype(str)
    a = np.char.replace(a, ',', '.')
    a = a.astype(float)
    print(a)
    
    # Out: [1.2 3.4 4.5 8.3 6.9]
    

    【讨论】:

    • 嗨!谢谢你的评论。我仍然遇到一个错误:无法将字符串转换为浮点数:'-' 我如何将此字符也转换为点?
    • "-" 此字符不会隐式转换为浮点数。这个字符如何驻留在您的数据中?你的预期输出是什么?可以举个例子吗?
    【解决方案2】:

    你可以试试

    int_X = int_X.astype(str)
    int_X = np.char.replace(X, ',', '.')
    

    例子

    int_X = np.array([34.12, 34.15, 56.15, "7,1", 80.16])
    int_X = int_X .astype(str)
    int_X = np.char.replace(int_X, ',', '.')
    int_X
    array(['34.12', '34.15', '56.15', '7.1', '80.16'], dtype='<U5')
    int_X = int_X.astype(float)
    int_X
    array([34.12, 34.15, 56.15,  7.1 , 80.16])
    

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 2020-03-08
      • 2011-07-02
      • 2012-04-26
      • 1970-01-01
      相关资源
      最近更新 更多