python - 合并数组和绘图

标签 python arrays numpy multidimensional-array

假设我有 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 的平均值或取该间隔的最大值)

最佳答案

我不知道你是否能在 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()。)

关于python - 合并数组和绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55430232/

相关文章:

python - 如何为我的 test.py 制作 Windows 独立安装程序

python - 避免 scrapy 上的重复值

python 在每个索引处对数组中的所有先前值求和

python - 为什么相同的 SQLite 查询在只获取两倍的结果时会慢 30 倍?

python - 从Python中的API展平嵌套的json

javascript - 在数组数组中查找一个值

arrays - 数组内的 C 联合多态性

c - 警告 : assignment makes integer from pointer without a cast in shellsort algorithm

python - 有没有一种快速的方法可以将 numpy 数组中的一个元素与该数组中的其余元素进行比较?

python - itertools 产品加速