首页 > 解决方案 > For 和 While 循环嵌套以创建滚动平均值

问题描述

所以我有一个数据框,其中情绪作为列标题,浮点分数作为行值,长度为 320,我正在尝试创建一个循环,对所有 4 种情绪系列中每 10 个分数的分数进行平均,所以我应该有 40 个平均值前 10 个代表快乐,接下来的 10 个代表悲伤等……理想情况下,将情绪存储为字典或新数据框,将情绪作为列,将平均分数作为行或值。

通过下面的循环,我得到了一些结果,但正确嵌套循环是问题所在。我相信有人可以指出我正确的方向。谢谢。

rolling_avgs = {}
emotions = ['happy', 'sad', 'bonding', 'leisure'] # aka my_df columns / rolling_avgs dict key values
i_i = [0, 1, 2, 3, 4, 5, 6] # indexer
i_s = 0 # start slice indexer
i_e = 12 # end slice endexer

for i in i_i:
  while i_e <= 320:

  # dict to capture the averages as values and emotion as keys
  rolling_avg[ emotions[i] ] = np.mean(my_df[emotions[i]].iloc[i_s:i_e])


  i_s += 10
  i_e += 10

标签: pythonfor-loopwhile-loopnested-loops

解决方案


推荐阅读