Home > Back-end >  How do I create a new column with values from the next row of another column in python?
How do I create a new column with values from the next row of another column in python?

Time:10-02

Say I have a dataframe as such:

id pos_X pos_y
1 100 0
2 68 17
3 42 28
4 94 35
5 15 59
6 84 19

This is my desired dataframe:

id pos_X pos_y pos_xend pos_yend
1 100 0 68 17
2 42 28 94 35
3 15 59 84 19

Basically the new column will have the values from the next row. How can I do this?

CodePudding user response:

I think you are taking alternate rows, so i would suggest something like this, considering data to be a pandas dataframe:

df = """your data"""
posx_end = df.loc[df['id'] % 2 ==0 ]['pos_X'].values
posy_end = df.loc[df['id'] % 2 ==0 ]['pos_y'].values

df = df.loc[df['id'] % 2 !=0].copy()
df['posx_end'] = posx_end
df['posy_end'] = posy_end

CodePudding user response:

You only need create a new DataFrame. You can build it with a "for" that travell around the old dataframe

import pandas as pf

old_datas = {'id':[1,2],'pos_x':[100,68],'pos_y':[0,17]}
old_df = pf.DataFrame(data=old_datas)

new_pos_x = []
new_pos_y = []
pos_xend = []
pos_yend = []
new_id =[]
for i in range(len(old_df)):
        if i%2:
            new_pos_x.append(old_df.iloc[i]['pos_x'])
            new_pos_y.append(old_df.iloc[i]['pos_y'])
            new_id.append(i)
        else:
            pos_xend.append(old_df.iloc[i]['pos_x'])
            pos_yend.append(old_df.iloc[i]['pos_y'])
new_datas = {'id':new_id,'pos_x':new_pos_x,'pos_y':new_pos_y,'pos_xend':pos_xend,'pos_yend':pos_yend}
new_df = pf.DataFrame(data=new_datas)

print(new_df)

CodePudding user response:

# select alternate row, first starting from 0, second from 1
# reset index and concat based on the index

# choose columns to use in concat
df2=pd.concat(
    [df.loc[ ::2][['id','pos_X', 'pos_y']].reset_index(drop=True) ,
     df.loc[1::2][['pos_X', 'pos_y']]    .reset_index(drop=True) .add_suffix('end')
          ],
         axis=1) 

# reset the ID column
df2['id']=np.arange(0, len(df2))
df2

or

# drop the extra column after concat

df2=pd.concat([df.loc[ ::2].reset_index(drop=True) ,
               df.loc[1::2].reset_index(drop=True) .add_suffix('end')
          ],
         axis=1).drop(columns='idend') 
# reset the ID column
df2['id']=np.arange(0, len(df2))
df2
   id   pos_X   pos_y   pos_Xend    pos_yend
0   0    100        0        68           17
1   1     42       28        94           35
2   2     15       59        84           19

CodePudding user response:

Selecting odd and even rows then concatenating them would solve the problem. Something like this

import pandas as pd

df = pd.DataFrame({'X':[100,68,12,6,21] , 'Y':[0,17,32,23,14]})
print(df)

# select even and odd rows
even_df = df.iloc[::2].reset_index(drop=True)
odd_df = df.iloc[1::2].reset_index(drop=True)  # odd

# concatente columns
result = pd.concat( [even_df, odd_df], axis=1)
print(result)

CodePudding user response:

You can use a pivot:

out = (df
   .drop(columns='id')
   .assign(idx=np.arange(len(df))//2,
           col=np.where(np.arange(len(df))%2, '', 'end'))
   .pivot(index='idx', columns='col')
   .pipe(lambda d: d.set_axis(d.columns.map(''.join), axis=1))
)

output:

     pos_X  pos_Xend  pos_Y  pos_Yend
idx                                  
0       68       100     17         0
1       94        42     35        28
2       64        15     19        59
  • Related