繁体   English   中英

替换 np.array 中的字符串字符

[英]Replace string character in np.array

我有一个 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')

我想用“。”替换“,”。 使用这个 function:

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

但我收到此错误:

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

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

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

看看下面的示例代码片段。 我已经将数组转换为 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]

你可以试试

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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM