I have a dataframe with n rows and m columns (an example of 6X5 is given below). I would like to add the (n+1)th row to the dataframe such that each cell in this row has a value equal to an earlier row depending on the position of the cell. The 1st cell would get the very first older value in the 1st column, the 2nd cell would get the next older value in the 2nd column,… and the mth cell will take the oldest value in the same mth column.
The original dataframe:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
The desired dataframe:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
21 17 13 9 5
Note that m and n must be generic so that the defined function can be applied to any dataframe and it is the fasted runtime-wise.
>Solution :
Try using np.diag()
df.iloc[-1] = np.diag(df.iloc[df.shape[0]-2::-1])
Output:
0 1 2 3 4
0 1 2 3 4 5
1 6 7 8 9 10
2 11 12 13 14 15
3 16 17 18 19 20
4 21 22 23 24 25
5 21 17 13 9 5