[英]Element wise average of arrays with different lengths from a dataframe
首先,我将解释我希望发生的事情。 我有很多 arrays,但以 3 为例,长度不同。 我想通过比较每个元素的 arrays 来获得平均值。
A = [0,10,20]
B = [10,40,60,80]
C = [50,70]
Expected outcome = [20,40,40,80]
我尝试过的是使用 itertools 中的 zip_longest 并使用统计数据中的平均值 function。
from itertools import zip_longest
from statistics import mean
outcome = [mean(n) for n in zip_longest(a, b, c, fillvalue=0)]
然而,正如指定的那样,填充值为 0,因此结果不是期望的结果。 由于使用平均值 function,我无法将填充值设置为无。 我是否必须使用不同的 function 来计算平均值? 或者另一种方法来获得不同长度的元素明智的平均值 arrays。
编辑:抱歉,但忘记谈论 arrays 的起源。因此 arrays 来自 pandas dataframe,其中列的每一行中的值是 x 长度的数组。
Edit2:添加更有意义的数据
使用 csv 文件的 pandas 创建 dataframe
Select 部分 dataframe 有 2 个条件
尝试从满足 2 个条件的第 3 列中获取元素明智的平均值
df = pd.read_csv('data.csv')
sec1 = df[(df['Color'] == 'blue') & (df['Type'] == 21)
outcome = [np.nanmean(n) for n in zip_longest(sec1['time'], fillvalue=float("nan"))]
print(outcome)
其中 sec1['time'] 有 output 其中 arrays 是不同的长度
2168 [0, 10, 20, 29, 44, 47, 59, 71, 94, 198...
2169 [0, 0, 7, 12, 47, 84, 144, 163, 222...
...
一种方法是使用nan
作为填充值并在计算平均值时过滤掉(使用filterfalse
)值,如下所示:
from itertools import zip_longest, filterfalse
from statistics import mean
from math import isnan
a = [0, 10, 20]
b = [10, 40, 60, 80]
c = [50, 70]
outcome = [mean(filterfalse(isnan, n)) for n in zip_longest(a, b, c, fillvalue=float("nan"))]
print(outcome)
Output
[20, 40, 40, 80]
我建议你使用fmean
:
outcome = [fmean(filterfalse(isnan, n)) for n in zip_longest(a, b, c, fillvalue=float("nan"))]
print(outcome)
比mean
快,来自文档:
这比 mean() function 运行得更快,它总是返回一个浮点数。 数据可以是序列或可迭代的。 如果输入数据集为空,则引发 StatisticsError。
另一种选择是使用 numpy nanmean
:
from itertools import zip_longest
import numpy as np
a = [0, 10, 20]
b = [10, 40, 60, 80]
c = [50, 70]
outcome = [np.nanmean(n) for n in zip_longest(a, b, c, fillvalue=float("nan"))]
print(outcome)
Output
[20.0, 40.0, 40.0, 80.0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.