我的代码中有如下内容:
mean_realp = [[df[(df['fvpwm'] == v) & (df['gppwm'] == w)]['P'].mean() for v in uvpwms] for w in upwms]
mean_setp = [[df[(df['fvpwm'] == v) & (df['gppwm'] == w)]['pressure setpoint [mbar]'].mean() for v in uvpwms] for w in upwms]
stddev_realp = [[df[(df['fvpwm'] == v) & (df['gppwm'] == w)]['P'].std() for v in uvpwms] for w in upwms]
stddev_pbefore = [[df[(df['fvpwm'] == v) & (df['gppwm'] == w)]['Pbefore [mbar]'].std() for v in uvpwms] for w in upwms]
maxes_realp = [[df[(df['fvpwm'] == v) & (df['gppwm'] == w)]['P'].max() for v in uvpwms] for w in upwms]
mins_realp = [[df[(df['fvpwm'] == v) & (df['gppwm'] == w)]['P'].min() for v in uvpwms] for w in upwms]
有没有一种方法可以简化此过程,而无需使用外部循环?我没有什么反对他们的,但必须有一个更优雅的解决方案...
对于后一部分
for v in uvpwms] for w in upwms]
我想不出比外循环更简单的东西。
但是内在部分呢?是否有一些更简单的解决方案(例如lambda表达式)?
答案 0 :(得分:1)
提供帮助功能以强调和参数化差异。这是一个开始,您可能应该找到一个更合适的名称,以更好地与数据集的真实含义联系起来:
def transformMatrix(matrix, label, transformer):
return [[df[transformer((df['fvpwm'] == v) & (df['gppwm'] == w)][label]) for v in matrix] for w in matrix]
mean_realp = transformMatrix(upwms, 'P', lambda elements: elements.mean())
mean_setp = transformMatrix(upwms, 'pressure setpoint [mbar]', lambda elements: elements.mean())
stddev_realp = transformMatrix(upwms, 'P', lambda elements: elements.std())
stddev_pbefore = transformMatrix(upwms, 'Pbefore [mbar]', lambda elements: elements.std())
maxes_realp = transformMatrix(upwms, 'P', lambda elements: elements.max())
mins_realp = transformMatrix(upwms, 'P', lambda elements: elements.min())