替换 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')
我想用“.”替换“,”使用此功能:
int_X = X.replace(',','.')
但是我收到这个错误:
AttributeError: 'numpy.ndarray' object has no attribute 'replace'
有人可以帮我解决我需要使用的正确功能吗?谢谢
.replace()
是一个字符串方法,所以它不会直接作用于 numpy 数组。您可以定义一个函数来对输入字符串执行此操作,然后将该函数矢量化以直接将其应用于数组的所有元素。
看看下面的示例代码片段。我已将数组转换为 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])
我有一个 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'
有人可以帮我解决我需要使用的正确功能吗?谢谢
.replace()
是一个字符串方法,所以它不会直接作用于 numpy 数组。您可以定义一个函数来对输入字符串执行此操作,然后将该函数矢量化以直接将其应用于数组的所有元素。
看看下面的示例代码片段。我已将数组转换为 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])