Kamikaze K
Kamikaze K

Reputation: 191

Appending rows below and above with new row with new values

I have a dataframe withe the following format where the values are %h%%S

enter image description here

I would like to, for each row,fill a row above with a the value minus 1 and the following row with value plus one so that it would be something like this

enter image description here etc

I have tried looking at options of using df.ffill but with no lock

Upvotes: 0

Views: 29

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24322

try:

df['date']=pd.to_datetime(df['date'],format='%H%M%S')
df=df.reindex(df.index.repeat(3)).reset_index(drop=True)
s1=(df.index%3)==0
s2=(df.index%3)==2
df.loc[s1,'date']=df.loc[s1,'date']-pd.DateOffset(hours=1)
df.loc[s2,'date']=df.loc[s2,'date']+pd.DateOffset(hours=1)
df['date']=df['date'].dt.strftime('%H%M%S')

output of df:

  col1  col2    date
0   X   A       002230
1   X   A       012230
2   X   A       022230
3   Y   B       131245
4   Y   B       141245
5   Y   B       151245
6   Z   C       220130
7   Z   C       230130
8   Z   C       000130

Sample dateframe used by me:

df=pd.DataFrame({'col1': {0: 'X', 1: 'Y', 2: 'Z'},
                 'col2': {0: 'A', 1: 'B', 2: 'C'},
                 'date': {0: '012230', 1: '141245', 2: '230130'}})

Upvotes: 1

Related Questions