python-2.7 - 使用 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
解决方案
您需要先使宽度均匀化:
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
在加载文件时添加的,否则单行文件会生成一维数组而不是二维数组。
推荐阅读
- c# - 基于来自其他图像的调色板将位图图像转换为数组
- angular - Angular 测试反应式表单验证服务方法在方法内部获取控件
- python - Python:如何将值向量化插入到 list/np.array 中(以给定的概率)?
- c - Memleak 演示没有获得常驻内存
- python - 等敏感曲线绘制python
- excel - 数据透视图 --> 使用不同过滤器时崩溃
- google-bigquery - BigQuery UI 在查看特定视图时崩溃
- awk - 试图在 jq 中重现 awk
- phantomjs - 无法将 PhantomJS 与 ReadyAPI v3.9.1 集成
- r - 下载数据并添加到 Glob.Env