Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I've got a pandas dataframe. I want to 'lag' one of my columns. Meaning, for example, shifting the entire column 'gdp' up by one, and then removing all the excess data at the bottom of the remaining rows so that all columns are of equal length again.

df =

    y  gdp  cap

0   1    2    5

1   2    3    9

2   8    7    2

3   3    4    7

4   6    7    7

df_lag =

    y  gdp  cap

0   1    3    5

1   2    7    9

2   8    4    2

3   3    7    7

Anyway to do this?

1 Answer

0 votes
by (41.4k points)

For shifting the entire column: 

In [44]: df['gdp'] = df['gdp'].shift(-1)

In [45]: df

Out[45]: 

   y  gdp  cap

0  1    3    5

1  2    7    9

2  8    4    2

3  3    7    7

4  6  NaN    7

In [46]: df[:-1]                                                                                                                                                                                                                                                                                                               

Out[46]: 

   y  gdp  cap

0  1    3    5

1  2    7    9

2  8    4    2

3  3    7    7

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...