Shifting a Column Down by One

Shifting a column down by one

Use a combination of the very efficient transform and na.omit functions

df <- na.omit(transform(df, CCC = c(NA, CCC[-nrow(df)])))

How to move a column down one without deleting a row in R

You can use the lag() function from dplyr and set its defualt value appropriately:

library(dplyr)
df %>%
mutate(Region = lag(Region,
# if missing, as in first row, defaults to the first
# value of df$region.
default = first(Region)))

Shift values in single column of dataframe up

Your problem simplifies to:

  • Drop the first n elements in a vector
  • Pad n values of NA at the end

You can do this with a simple function:

shift <- function(x, n){
c(x[-(seq(n))], rep(NA, n))
}

example$z <- shift(example$z, 2)

The result:

example
x y z
1 1 1 3
2 2 2 4
3 3 3 5
4 4 4 6
5 5 5 7
6 6 6 8
7 7 7 NA
8 8 8 NA

Shift column in pandas dataframe up by one?

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

SQL Shift column down 1 row

You can use the LAG() function, as in:

select
d,
present,
lag(past, 1, 0) over (order by d) as past
from t
order by d

Result:

d          present past
---------- ------- ----
2019-01-01 100 0
2019-02-01 200 100
2019-03-01 300 200
2019-04-01 400 300

See SQL Fiddle.

For the record, here's the data script:

create table t (
d date,
present int,
past int
);

insert into t (d, present, past) values ('2019-01-01', 100, 100);
insert into t (d, present, past) values ('2019-02-01', 200, 200);
insert into t (d, present, past) values ('2019-03-01', 300, 300);
insert into t (d, present, past) values ('2019-04-01', 400, 400);

How to shift an entire column down (including the header) and then rename the header 'Name'?

Maybe this helps:

df = pd.DataFrame({'index': range(4), 'Patrick': ['Stan', 'Frank', 'Emily', 'Tami']})

names = pd.concat([pd.Series(df.columns[1]),df.iloc[:, 1]]).reset_index(drop=True)

df = pd.DataFrame({'Names': names})

df

index Names
0 Patrick
1 Stan
2 Frank
3 Emily
4 Tami


Related Topics



Leave a reply



Submit