Home > other >  Repeat the dataframe and increment the timestamps
Repeat the dataframe and increment the timestamps

Time:07-29

I have a dataframe like this

  Temp time[s] 
0 20    0
1 21    1
2 21.5  2

I want to repeat the dataframe but add the timestamp, my output should like this ,

Temp time[s] 
0 20    0
1 21    1
2 21.5  2
3 20    3
4 21    4
5 21.5  5

I tried something like this , but didn't worked for me

df2 = pd.concat([df]*2, ignore_index=True)
df2['time[s]'] = df2.groupby(level=0).cumcount() * 1

Can anyone help me plz ?

CodePudding user response:

For a generic approach, you can use:

N = 2 # number or repetitions
df2 = pd.concat([df]*N, ignore_index=True)
df2['time[s]']  = np.repeat(np.arange(N), len(df))*len(df)
# or
# df2['time[s]']  = np.arange(len(df2))//len(df)*len(df)

output:

   Temp  time[s]
0  20.0        0
1  21.0        1
2  21.5        2
3  20.0        3
4  21.0        4
5  21.5        5

CodePudding user response:

Try this for your exact use case with one repetition:

df_x = pd.concat([df, df]).reset_index(drop=True)
df_x["time[s]"] = df_x.index

Print out:

    Temp    time[s]
0   20.0    0
1   21.0    1
2   21.5    2
3   20.0    3
4   21.0    4
5   21.5    5
  • Related