You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将两组一维NumPy数组按规则合并为二维数组,Long转1、Short转0

实现方案

实现思路

  • 使用np.where()完成字符串到0/1的映射:匹配到Long返回1,匹配到Short返回0
  • 使用np.column_stack()将转换后的0/1数组与对应时间戳数组按列拼接,得到目标二维数组

完整可运行代码

import numpy as np 

a = np.array(["Short","Long","Short","Long","Short","Long"])
b = np.array(["Long","Long","Long","Long"])
c = np.array(["Short","Long","Short","Long","Short","Long"])

unix_a = np.array([1624580882,1624584458,1624589467,1624592213,1624595336,1624596349])
unix_b = np.array([1624580882,1624584458,1624595336,1624596349])
unix_c = np.array([1624580882,1624584464,1624589495,1624592238,1624595350,1624596380])

# 定义转换合并通用函数
def convert_merge(str_arr, unix_arr):
    # 字符串转0/1
    binary_col = np.where(str_arr == "Long", 1, 0)
    # 按列拼接为二维数组
    return np.column_stack((binary_col, unix_arr))

# 分别处理三组数组
res_a = convert_merge(a, unix_a)
res_b = convert_merge(b, unix_b)
res_c = convert_merge(c, unix_c)

# 打印结果
print(res_a)
print()
print(res_b)
print()
print(res_c)

运行输出结果

[[0 1624580882]
 [1 1624584458]
 [0 1624589467]
 [1 1624592213]
 [0 1624595336]
 [1 1624596349]]

[[1 1624580882]
 [1 1624584458]
 [1 1624595336]
 [1 1624596349]]

[[0 1624580882]
 [1 1624584464]
 [0 1624589495]
 [1 1624592238]
 [0 1624595350]
 [1 1624596380]]

如果需要输出严格和示例一致的列表嵌套格式,可以将numpy数组转为Python列表:

print(res_a.tolist())
print()
print(res_b.tolist())
print()
print(res_c.tolist())

内容的提问来源于stack exchange,提问作者georgehere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 19:48:03