[Python] How to concatenate n rows of content, to current row, in a rolling window, in pandas?

Discussão em 'Python' iniciado por Stack, Maio 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm looking to transform a dataframe containing

    [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

    into [[1, 2, 3, []], [4, 5, 6, [1, 2, 3, 4, 5, 6]], [7, 8, 9, [4, 5, 6, 7, 8, 9]], [10, 11, 12, [7, 8, 9, 10, 11, 12]]]

    So far the only working solution I've come up with is:

    import pandas as pd
    import numpy as np

    # Create the DataFrame
    df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]))

    # Initialize an empty list to store the result
    result = []

    # Iterate over the rows in the DataFrame
    for i in range(len(df)):
    # If it's the first row, append the row with an empty list
    if i == 0:
    result.append(list(df.iloc) + [[]])
    # If it's not the first row, concatenate the current and previous row
    else:
    current_row = list(df.iloc)
    previous_row = list(df.iloc[i-1])
    concatenated_row = current_row + [previous_row + current_row]
    result.append(concatenated_row)

    # Print the result
    print(result)


    Is there no build in Pandas function that can roll a window, and add the results to current row, like the above can?

    Continue reading...

Compartilhe esta Página