python - 连接两个numpy数组以使索引顺序保持不变?
问题描述
假设我有两个 numpy 数组,如下所示:
{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}
现在我想用前面的ID替换每个数组,即数组0中的值变为0,数组1中的值变为1,那么两个数组都应该合并,索引顺序必须正确。即期望的输出:
array([1, 0, 1, 0, 1, 0, 0 ,0])
但这就是我得到的:
np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])
(如果有帮助,每个数组只包含唯一值。)
如何才能做到这一点?
解决方案
您对合并的描述有点不清楚。但这是有道理的
In [399]: dd ={0: np.array([ 2, 4, 8, 9, 12]),
...: 1: np.array([ 1, 3, 5])}
In [403]: res = np.zeros(13, int)
In [404]: res[dd[0]] = 0
In [405]: res[dd[1]] = 1
In [406]: res
Out[406]: array([0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0])
或者使分配更清晰:
In [407]: res = np.zeros(13, int)
In [408]: res[dd[0]] = 2
In [409]: res[dd[1]] = 1
In [410]: res
Out[410]: array([0, 1, 2, 1, 2, 1, 0, 0, 2, 2, 0, 0, 2])
否则,谈话索引位置没有多大意义。
推荐阅读
- angularjs - Angular JS 中是否有来自 React JS 的等价道具?
- r - 如何使线条片段与ggplot中的单个点匹配
- python - 将组附加到熊猫数据框时导致值错误
- python - 如何输出字典值的排列
- html - CSS关键帧动画适用于Chrome桌面但不适用于移动设备?
- html - 让图像占据改变大小的 div 的全部高度?
- node.js - 在 React 中存储 Express 会话 ID
- r - 使用 lapply 按列对数据框列表进行分组
- node.js - 如何修复“× TypeError: Object(...) is not a function”?
- javascript - 将来自 google webapp 的字符串存储到数组中