简体   繁体   中英

how to move values in a pandas column from some position to another?

I have a dataframe df

   df:
         A   I
  Time
    7    3   7
   14    2   6
   21    5   5
   28    7   2
   35    3   0
   42    0  23
   49   -1  28

I would like to move the last two values of df['I'] in the column from position Time=21 in order to have

   df:
         A   I
  Time
    7    3   7
   14    2   6
   21    5  23
   28    7  28
   35    3   5
   42    0   2
   49   -1   0

I tried the following

def swapper(tmp):
    tmp = tmp.reset_index(drop=True)
    tmp['I'][2:4] = tmp['I'][4:6]
    tmp['I'][4:6] = tmp['I'][2:4]
    return tmp

No special Pandas way but you can do it like this:

def swapper(old, new, df, col_name):
    if len(old) != len(new):
        return "Lists must be equal"
    else:
        for i in zip(old,new):
            temp = df.loc[i[0], col_name]
            df.loc[i[0], col_name] = df.loc[i[1], col_name]
            df.loc[i[1], col_name] = temp
    return

swapper([21,28], [42,49], df, 'I')


    A   I
Time        
7   3   7
14  2   6
21  5   23
28  7   28
35  3   0
42  0   5
49  -1  2

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