“合并" numpy数组以及一个共同的维度 [英] "Merging" numpy arrays together with a common dimension
问题描述
我有两个矩阵,分别对应于数据点(x,y1)
和(x,y2)
:
I have two matricies, corresponding to data points (x,y1)
and (x,y2)
:
x | y1
------------
0 | 0
1 | 1
2 | 2
3 | 3
4 | 4
5 | 5
x | y2
----------------
0.5 | 0.5
1.5 | 1.5
2.5 | 2.5
3.5 | 3.5
4.5 | 4.5
5.5 | 5.5
我想创建一个新的矩阵,该矩阵将x
值合并到单个列中,并在相应的y1
,y2
列中包含NaN
s:
I'd like to create a new matrix that combines the x
values into a single column, and has NaN
s in the appropriate y1
, y2
columns:
x | y1 | y2
-----------------------------
0 | 0 | NaN
0.5 | NaN | 0.5
1 | 0 | NaN
1.5 | NaN | 1.5
... | ... | ...
5 | 5 | NaN
5.5 | NaN | 5.5
有没有简单的方法可以做到这一点?我是Python和NumPy(来自MATLAB)的新手,我不确定如何开始. (作为参考,我在MATLAB中对此的处理方法只是使用 outerjoin
反对使用 array2table
.)
Is there an easy way to do this? I'm new to Python and NumPy (coming from MATLAB) and I'm not sure how I would even begin with this. (For reference, my approach to this in MATLAB is simply using an outerjoin
against two tables that are generated with array2table
.)
推荐答案
如果可以将数据加载到单独的pandas
数据帧中,这将变得很简单.
If you can load your data into separate pandas
dataframes, this becomes simple.
df
x y1
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
df2
x y2
0 0.5 0.5
1 1.5 1.5
2 2.5 2.5
3 3.5 3.5
4 4.5 4.5
5 5.5 5.5
执行外部merge
,然后在x
列上进行排序.
Perform an outer merge
, and sort on the x
column.
df = df.merge(df2, how='outer').sort_values('x')
df
x y1 y2
0 0 0 NaN
6 0.5 NaN 0.5
1 1 1 NaN
7 1.5 NaN 1.5
2 2 2 NaN
8 2.5 NaN 2.5
3 3 3 NaN
9 3.5 NaN 3.5
4 4 4 NaN
10 4.5 NaN 4.5
5 5 5 NaN
11 5.5 NaN 5.5
如果需要数组,请在结果上调用.values
:
If you want an array, call .values
on the result:
df.values
array([[0.0, 0.0, nan],
[0.5, nan, 0.5],
[1.0, 1.0, nan],
[1.5, nan, 1.5],
[2.0, 2.0, nan],
[2.5, nan, 2.5],
[3.0, 3.0, nan],
[3.5, nan, 3.5],
[4.0, 4.0, nan],
[4.5, nan, 4.5],
[5.0, 5.0, nan],
[5.5, nan, 5.5]], dtype=object)
这篇关于“合并" numpy数组以及一个共同的维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!