Python Forum

Full Version: Explain the python code in this definition
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I found the following python o online and it looks very useful to me.

def get_mean_features(sensor_list, df):
    """
    Function to get mean val of 10min window
    """

    new_features = {}

    # looping over all sensors and calculating mean of 10 values
    for sensor in sensor_list:
        new_features[sensor] = df[sensor].rolling(10).mean().values

    labels = []
    # creating list with None value
    labels = [None] * (df.shape[0])

    for i in range(0, df.shape[0]-10):
        labels[i+9] = df['label'][i+10]

    new_features['label'] = labels

    # creating dataframe
    new_df = pd.DataFrame(new_features)
    # removing first 9 rows with null values
    new_df.drop(new_df.head(9).index, inplace=True)
    # resetting index 
    new_df.reset_index(inplace=True, drop=True)
    # dropping last row with null value
    new_df.drop(new_df.tail(1).index, inplace=True)
    return new_df
I have several questions on this code. I just want to start off by asking why these two lines.

    new_features = {}

    labels = []
   
why the two different delimiters brackets and braces? Why not just one set of brackets or braces?

Any help appreciated.

Respectfully,

LZ
new_features = {} makes an empty dictionary.
labels = [] makes an empty list

But you know that already. What is the real question?

I think I've responded to 2 or 3 of your posts showing how to do a rolling mean. One of those times I even presented the results of a timing test showing that using rolling() was 4000 times faster than the method you used to compute a rolling mean. Now you think this code looks like it could be useful, sounding like it is something completely new to you.