简体   繁体   中英

How to concat rows(axis=1) with stride?

example:

import pandas as pd

test = {
    't':[0,1,2,3,4,5], 
    'A':[1,1,1,2,2,2], 
    'B':[9,9,9,9,8,8], 
    'C':[1,2,3,4,5,6]
   }

df = pd.DataFrame(test)
df

在此处输入图像描述

Tried use window and concat:

window_size = 2

for row_idx in range(df.shape[0] - window_size):
    print(
        pd.concat(
            [df.iloc[[row_idx]],
             df.loc[:, df.columns!='t'].iloc[[row_idx+window_size-1]],
             df.loc[:, df.columns!='t'].iloc[[row_idx+window_size]]],
            axis=1
        )
    )

But get wrong dataframe like this:

在此处输入图像描述

Is it possible to use a sliding window to concat data?

在此处输入图像描述

pd.concat is alingning indices, so you have to make sure that they fit. You could try the following:

window_size = 2
dfs = []
for n in range(window_size + 1):
    sdf = df.iloc[n:df.shape[0] - window_size + n]
    if n > 0:
        sdf = (
            sdf.drop(columns="t").rename(columns=lambda c: f"{c}_{n}")
            .reset_index(drop=True)
        )
    dfs.append(sdf)
res = pd.concat(dfs, axis=1)

Result for the sample:

   t  A  B  C  A_1  B_1  C_1  A_2  B_2  C_2
0  0  1  9  1    1    9    2    1    9    3
1  1  1  9  2    1    9    3    2    9    4
2  2  1  9  3    2    9    4    2    8    5
3  3  2  9  4    2    8    5    2    8    6

Have a look at this example below:

    df1 = pd.DataFrame([['a', 1], ['b', 2]],
                   columns=['letter', 'number'])
    df4 = pd.DataFrame([['bird', 'polly'], ['monkey','george']],
                       columns=['animal', 'name'])
    pd.concat([df1, df4], axis=1)
    # Returns the following output
      letter  number  animal    name
    0      a       1    bird   polly
    1      b       2  monkey  george

It was taken from the followingpandas doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM