Search code examples
pythonpython-3.xpandaspython-itertools

Dataset using iterative hilt in windowing


This is my true code, but I haven't true output

import itertools as it
import numpy as np
import pandas as pd

x = [1,2,3,4,5,6,7,8,9,10]
def moving_window(x, length, step=1):
    streams = it.tee(x, length)
    return zip(*[it.islice(stream, i, None, step+2) for stream, i in zip( streams,it.count(step=step))])
x_=list(moving_window(x,6))

for i in range(len(x_)):
    globals()['a'+str(i)] = list(x_[i])
    print(x_[i])

def mean(dataset):
    return sum(dataset) / len(dataset)
for i in range(len(x_)):
    globals()['a'+str(i)] = list(x_[i])
    a=mean(x_[i])
    print(a)

This output now is:

   3.5
   6.5

But I want a code with the following output:

| A header | Another header |


| a1   | 3.5           |

| a2   | 6.5           |

These rows and columns continue


Solution

  • Are you wanting this:

    dct = {}
    for i in range(len(x_)):
        globals()['a'+str(i)] = list(x_[i])
        a=mean(x_[i])
        dct[f'a{i+1}'] = a
        print(a)
    

    Output:

    >>> dct
    {'a1': 3.5, 'a2': 6.5}
    

    Update:

    >>> df = pd.DataFrame(dct.items(), columns=['A header', 'Another header'])
    >>> df
        A header    Another header
    0         a1    3.5
    1         a2    6.5