合并数组和图

问题描述 投票:2回答:3

假设我有2个这样的数组:

x1 = [ 1.2,  1.8,  2.3,  4.5, 20.0]
y1 = [10.3, 11.8, 12.3, 11.5, 11.5]

和其他两个代表相同功能但以不同值采样的

x2 = [ 0.2,  1,8,  5.3, 15.5, 17.2, 18.3, 20.0]
y2 = [10.3, 11.8, 12.3, 12.5, 15.2, 10.3, 10.0]

是否有一种方法,numpy合并x1和x2,并根据结果合并y的相关值,而不显式循环遍及数组? (比如做y的平均值或在该间隔内取最大值)

python arrays numpy multidimensional-array
3个回答
1
投票

我不知道你是否能找到numpy中的东西,但这里有一个使用pandas的解决方案。 (Pandas在幕后使用numpy,因此没有那么多的数据转换。)

import numpy as np 
import pandas as pd 
x1 = np.asarray([ 1.2,  1.8,  2.3,  4.5, 20.0])
y1 = np.asarray([10.3, 11.8, 12.3, 11.5, 11.5])
x2 = np.asarray([ 0.2,  1.8,  5.3, 15.5, 17.2, 18.3, 20.0])
y2 = np.asarray([10.3, 11.8, 12.3, 12.5, 15.2, 10.3, 10.0])
c1 = pd.DataFrame({'x': x1, 'y': y1})
c2 = pd.DataFrame({'x': x2, 'y': y2})
c = pd.concat([c1, c2]).groupby('x').mean().reset_index()
x = c['x'].values
y = c['y'].values

# Result:
x = array([ 0.2,  1.2,  1.8,  2.3,  4.5,  5.3,  15.5, 17.2, 18.3, 20. ])
y = array([10.3 , 10.3, 11.8, 12.3, 11.5, 12.3, 12.5, 15.2, 10.3, 10.75])

在这里,我连接两个向量并执行groupby操作以获得'x'的相等值。对于这些“群体”,我采取的意思是()。 reset_index()将把索引'x'移回一列。为了将结果作为一个numpy数组返回,我使用.values。 (对于pandas 24.0及更高版本,请使用to_numpy()。)


0
投票

如何使用numpy.hstack然后使用numpy.sort进行排序?

In [101]: x1_arr = np.array(x1)
In [102]: x2_arr = np.array(x2)

In [103]: y1_arr = np.array(y1)
In [104]: y2_arr = np.array(y2)


In [111]: np.sort(np.hstack((x1_arr, x2_arr)))
Out[111]: 
array([ 0.2,  1.2,  1.8,  1.8,  2.3,  4.5,  5.3, 15.5, 17.2, 18.3, 20. ,
       20. ])

In [112]: np.sort(np.hstack((y1_arr, y2_arr)))
Out[112]: 
array([10. , 10.3, 10.3, 10.3, 11.5, 11.5, 11.8, 11.8, 12.3, 12.3, 12.5,
       15.2])

如果你想摆脱重复,你可以在上面的结果之上应用numpy.unique


0
投票

我会根据this question的接受答案提出一个解决方案:

import numpy as np
import pylab as plt

x1 = [1.2, 1.8, 2.3, 4.5, 20.0]
y1 = [10.3, 11.8, 12.3, 11.5, 11.5]

x2 = [0.2, 1.8, 5.3, 15.5, 17.2, 18.3, 20.0]
y2 = [10.3, 11.8, 12.3, 12.5, 15.2, 10.3, 10.0]

# create a merged and sorted x array
x = np.concatenate((x1, x2))
ids = x.argsort(kind='mergesort')
x = x[ids]

# find unique values
flag = np.ones_like(x, dtype=bool)
np.not_equal(x[1:], x[:-1], out=flag[1:])

# discard duplicated values
x = x[flag]

# merge, sort and select values for y
y = np.concatenate((y1, y2))[ids][flag]

plt.plot(x, y, marker='s', color='b', ls='-.')
plt.xlabel('x')
plt.ylabel('y')

plt.show()

这是结果:enter image description here

x = [ 0.2  1.2  1.8  2.3  4.5  5.3 15.5 17.2 18.3 20. ] 
y = [10.3 10.3 11.8 12.3 11.5 12.3 12.5 15.2 10.3 11.5]

正如您所注意到的,如果y有几个可用的代码,则此代码只为x保留一个值:这样代码更快。

额外的解决方案:以下解决方案基于循环,主要是标准的Python函数和对象(不是numpy),所以我知道它是不可接受的;顺便说一句,它是非常巧合和优雅的,它为y处理多个值,所以我决定将它包含在这里作为一个加号:

x = sorted(set(x1 + x2))
y = np.nanmean([[d.get(i, np.nan) for i in x] 
                for d in map(lambda a: dict(zip(*a)), ((x1, y1), (x2, y2)))], axis=0)

在这种情况下,您将获得以下结果:

x = [0.2, 1.2, 1.8, 2.3, 4.5, 5.3, 15.5, 17.2, 18.3, 20.0] 
y = [10.3  10.3  11.8  12.3  11.5  12.3  12.5  15.2  10.3  10.75]
© www.soinside.com 2019 - 2024. All rights reserved.