Home > front end >  Generate dataframe columns where each column is shift(-1) of previous column
Generate dataframe columns where each column is shift(-1) of previous column

Time:11-18

I want to create 44 dataframe columns based on TAZ_1720 such that each column is shift(-1) of the previous column.

How can I do it instead of writing it 44 times?

df['m1']=df['TAZ_1270'].shift(-1)
df['m2']=df['m1'].shift(-1)
df['m3']=df['m2'].shift(-1)

table

CodePudding user response:

Use DataFrame.assign with a dict comprehension.

Here is a minimal example with 4 shifts:

df = pd.DataFrame({'TAZ_1270': [100047, 100500, 100488, 100099]})

#    TAZ_1270
# 0    100047
# 1    100500
# 2    100488
# 3    100099
df = df.assign(**{f'm{i}': df['TAZ_1270'].shift(-i) for i in range(1, 5)})

#    TAZ_1270        m1        m2        m3  m4
# 0    100047  100500.0  100488.0  100099.0 NaN
# 1    100500  100488.0  100099.0       NaN NaN
# 2    100488  100099.0       NaN       NaN NaN
# 3    100099       NaN       NaN       NaN NaN
  • Related