简体   繁体   中英

Shift Data and create new column - python dataframe

I am working on a problem, which needs to shift data from a column by 1,2 and 3 ..and the create new column for that vaue.

Example DataFrame:

Date     Price 
1-1-18     10
2-1-18     20
3-1-18     25
4-1-18     30
5-1-18     45
6-1-18     50
7-1-18     60

Expected DataFrame :

Date    Price    Price1    Price2    Price3
1-1-18   10        -1       -1        -1
2-1-18   20        -1       -1        -1
3-1-18   25        -1       -1        -1
4-1-18   30        25       20        10
5-1-18   45        30       25        20
6-1-18   50        45       30        25
7-1-18   60        50       45        30

First create new columns with shift by range and then set -1 :

N = 3
for x in range(1, N + 1):
    #python 3.6+ 
    df[f'Price{x}'] = df['Price'].shift(x)
    #python bellow
    #df['Price{}'.format(x)] = df['Price'].shift(x)

df.iloc[:N, -N:] = -1
print (df)
     Date  Price  Price1  Price2  Price3
0  1-1-18     10    -1.0    -1.0    -1.0
1  2-1-18     20    -1.0    -1.0    -1.0
2  3-1-18     25    -1.0    -1.0    -1.0
3  4-1-18     30    25.0    20.0    10.0
4  5-1-18     45    30.0    25.0    20.0
5  6-1-18     50    45.0    30.0    25.0
6  7-1-18     60    50.0    45.0    30.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM