gpt4 book ai didi

python - 基于元素函数将 1d numpy 数组映射到 2d 数组

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:17 24 4
gpt4 key购买 nike

我有一个 numpy 数组,它有 shape=(10000,)。以下是前 5 个条目:

labels = data[:, 0]
print(labels.shape)
print(labels[0:5])

# prints
# (100000,)
# [1. 1. 1. 0. 1.]

每个条目要么是 0 要么是 1。我想通过映射的元素明智的操作将其映射到二维数组

0 -> [1, 0]
1 -> [0, 1]

我该怎么做?我试过了

labels = np.apply_along_axis(lambda x: [1, 0] if x[0] == 0 else [0, 1], 0, data[:, 0])

但这似乎没有用。

最佳答案

In [435]: ref = np.array([[1,0],[0,1]])
In [436]: index = np.array([1.,1.,1.,0.,1.])

使用 float 索引在最新版本中会出错:

In [437]: ref[index,:]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-437-d50c95668d6c> in <module>()
----> 1 ref[index,:]

IndexError: arrays used as indices must be of integer (or boolean) type

整数索引,根据 index 值从 ref 中选择行:

In [438]: ref[index.astype(int),:]
Out[438]:
array([[0, 1],
[0, 1],
[0, 1],
[1, 0],
[0, 1]])

这是可以使用 choose 的情况,但它对数组形状比上述索引更挑剔:

In [440]: np.choose(index.astype(int)[:,None],[[1,0],[0,1]])
Out[440]:
array([[0, 1],
[0, 1],
[0, 1],
[1, 0],
[0, 1]])

或者只有 2 个选择转换为 bool 值,where:

In [443]: np.where(index.astype(bool)[:,None],[0,1],[1,0])
Out[443]:
array([[0, 1],
[0, 1],
[0, 1],
[1, 0],
[0, 1]])

关于python - 基于元素函数将 1d numpy 数组映射到 2d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269042/

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