gpt4 book ai didi

python - 基于唯一值的列字符串转换

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:57 25 4
gpt4 key购买 nike

有没有办法用 Python 中的有序数字替换二维数组列中的字符串值?

例如假设您有一个二维数组:

a = np.array([['A',0,'C'],['A',0.3,'B'],['D',1,'D']])
a
Out[57]:
array([['A', '0', 'C'],
['A', '0.3', 'B'],
['D', '1', 'D']], dtype='<U3')

如果我想将第一列中的字符串值 'A','A','D' 替换为数字 0,0,1 并将 'C','B','D' 替换为 0,1 ,2 是否有有效的方法。

了解以下内容可能会有所帮助:

  • 不同列中的替换数字与列无关。即,字符串被替换为数字的每一列将从 0 开始,并增加到该列中唯一值的数量。
  • 以上是一个测试用例,实际数据更大,字符串列更多。

这是我很快想出的解决这个问题的示例方法:

for  j in range(a.shape[1]):
b = list(set(a[:,j]))
length = len(b)
for i in range(len(b)):
indices = np.where(a[:,j]==b[i])[0]
print(indices)
a[indices,j]=i

然而,这似乎是一种低效的实现方式,而且无法区分列中的浮点值或字符串值,并且默认情况下用数字字符串替换值:

a
Out[91]:
array([['1.0', '0.0', '2.0'],
['1.0', '1.0', '0.0'],
['0.0', '2.0', '1.0']], dtype='<U3')

如有任何帮助,我们将不胜感激!

最佳答案

看来您正在尝试进行标签编码

我可以想到两个选项:pandas.factorizesklearn.preprocessing.LabelEncoder .

使用LabelEncoder

from sklearn.preprocessing import LabelEncoder

b = np.zeros_like(a, np.int)
for column in range(a.shape[1]):
b[:, column] = LabelEncoder().fit_transform(a[:, column])

那么 b 将是:

array([[0, 0, 1],
[0, 1, 0],
[1, 2, 2]])

如果您希望能够返回到原始值,则需要保存编码器。你可以这样做:

from sklearn.preprocessing import LabelEncoder

encoders = {}
b = np.zeros_like(a, np.int)
for column in range(a.shape[1]):
encoders[column] = LabelEncoder()
b[:, column] = encoders[column].fit_transform(a[:, column])

现在 encoders[0].classes_ 将有:

array(['A', 'D'], dtype='<U3')

这意味着“A”被映射到 0,“D”被映射到 1

最后,如果您执行编码覆盖 a 而不是使用新矩阵 c,您将获得整数作为字符串 ("1" 而不是 1),您可以使用 astype(int) 解决此问题:

encoders = {}
for column in range(a.shape[1]):
encoders[column] = LabelEncoder()
a[:, column] = encoders[column].fit_transform(a[:, column])

# At this point, a will have strings instead of ints because a had type str
# array([['0', '0', '1'],
# ['0', '1', '0'],
# ['1', '2', '2']], dtype='<U3')

a = a.astype(int)

# Now `a` is of type int
# array([[0, 0, 1],
# [0, 1, 0],
# [1, 2, 2]])

使用pd.factorize

factorize 返回编码列和编码映射,所以如果您不关心它,您可以避免保存它:

for column in range(a.shape[1]):
a[:, column], _ = pd.factorize(a[:, column]) # Drop mapping

a = a.astype(int) # same as above, it's of type str
# a is
# array([[0, 0, 1],
# [0, 1, 0],
# [1, 2, 2]])

如果你想保留编码映射:

mappings = []
for column in range(a.shape[1]):
a[:, column], mapping = pd.factorize(a[:, column])
mappings.append(mapping)

a = a.astype(int)

现在 mappings[0] 将具有以下数据:

array(['A', 'D'], dtype=object)

它与 sklearn 的 LabelEncoder 解决方案的 encoders[0].classes_ 具有相同的语义。

关于python - 基于唯一值的列字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53393087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com