首页 > 解决方案 > 使用 Vstack Python 合并字符串的不同维度或列

问题描述

这是上一个问题的延续。如何将 vstack 用于这些示例中的不同维度或列。

File : "new.dat"
WBGG 120200Z VRB03KT 030V170 9000 FEW015 BKN160 28/25 Q1013 NOSIG

File : "old.dat"
WBGG 120130Z VRB02KT 9000 FEW015 BKN150 27/25 Q1013 NOSIG    
WBGG 120100Z VRB02KT 9999 FEW014 BKN150 26/25 Q1012 NOSIG

@Anton vBR 建议使用的脚本如下,但它仅适用于类似的维度。

a = np.loadtxt('old.dat', dtype='object')
b = np.loadtxt('new.dat', dtype='object')

c = np.vstack((b,a))

np.savetxt('old.dat', c, delimiter=" ", fmt="%s")

预期输出为:

WBGG 120200Z VRB03KT 030V170 9000 FEW015 BKN160 28/25 Q1013 NOSIG
WBGG 120130Z VRB02KT 9000 FEW015 BKN150 27/25 Q1013 NOSIG    
WBGG 120100Z VRB02KT 9999 FEW014 BKN150 26/25 Q1012 NOSIG

标签: python-2.7

解决方案


您需要先使宽度均匀化:

a = np.loadtxt('old.dat', dtype='object', ndmin=2)
b = np.loadtxt('new.dat', dtype='object', ndmin=2)

a_width = a.shape[1]
b_width = b.shape[1]
if a_width < b_width:
    a = np.append(a, np.zeros((len(a), b_width - a_width), 'S0'), axis=1) # 'U0' in Python 3
if b_width < a_width:
    b = np.append(b, np.zeros((len(b), a_width - b_width), 'S0'), axis=1)

然后它将起作用。

请注意,我是ndmin=2在加载文件时添加的,否则单行文件会生成一维数组而不是二维数组。


推荐阅读