我有这种形式的DataFrame:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
# generate contrived data
df = pd.DataFrame({"Timestep" : np.arange(1000),
"Sensor Reading" : np.sin(np.arange(1000) * 2 * np.pi/100.0) + 0.1 * np.random.standard_normal(1000),
"Label" : np.repeat(np.arange(10), [96, 107, 95, 104, 97, 100, 105, 103, 100, 93])
})
plt.plot(df["Sensor Reading"])
plt.figure()
基本上,我有10个由“标签”列标识的时段,每个时段都有来自传感器的约100个嘈杂的读数。
我想通过堆叠/对齐10个周期中的每个周期(修剪到最短的周期)并获得每个时间点的平均值来获得平均信号。我可以使用以下代码迭代地执行此操作:
grouped = df.groupby("Label")
# current method
grouplength = min(len(g) for k, g in grouped)
reference_result = np.zeros(grouplength)
for k, group in grouped:
reference_result += group["Sensor Reading"][:grouplength]/len(grouped)
即看起来像这样:
但是我无法弄清楚如何使用按功能分组(转换,应用等)来达到相同的结果。如何使用熊猫以简洁的方式做到这一点?
(请注意:在完整的应用中,这不是正弦波,而是对每个周期开始时发出的信号的测量物理响应。因此,我不希望找到一种可靠的方式来对齐信号或检测频率。 )
您可以使用cumcount
(0.13中的新增功能)更有效地做到这一点:
grouplength = grouped.size().min()
cumcount = grouped.cumcount()
sub_df = df.loc[cumcount < grouplength, 'Sensor Reading']
如果索引是唯一的,则可以对进行分组cumcount
并取均值:
reference_result = sub_df.groupby(cumcount).mean().values
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句