Create New Pandas DataFrame Column Equaling Values From Other Row in Same DataFrame

Assuming that the DataFrame is:

       TimeStamp  Price  OtherData1  OtherData2  Fut2Min
0  1603822620000    101           1           8        0
1  1603822680000    105           2           7        0
2  1603822740000    102           3           6        0
3  1603822800000    108           4           5        0
4  1603823040000    105           5           4        0
5  1603823100000    101           6           3        0
6  1603823160000    106           7           2        0
7  1603823220000    111           8           1        0

Then, if you use pandas.DataFrame.apply, along the column axis:

import pandas as pd

def Fut2MinFunc(row):
    futTimeStamp = row.TimeStamp + 120000
    if (futTimeStamp in df.TimeStamp.values):
        return df.loc[df['TimeStamp'] == futTimeStamp, 'Price'].iloc[0]
    else:
        return None

df['Fut2Min'] = df.apply(Fut2MinFunc, axis = 1)

You will get exactly what you describe as:

       TimeStamp  Price  OtherData1  OtherData2  Fut2Min
0  1603822620000    101           1           8    102.0
1  1603822680000    105           2           7    108.0
2  1603822740000    102           3           6      NaN
3  1603822800000    108           4           5      NaN
4  1603823040000    105           5           4    106.0
5  1603823100000    101           6           3    111.0
6  1603823160000    106           7           2      NaN
7  1603823220000    111           8           1      NaN

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top