Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify a generic dataframe by shifting one of its rows using a python function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading