如何将熊猫列中的值从某个位置移动到另一个位置?

时间:2019-02-27 12:44:59

标签: python pandas

我有一个数据框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

我想从位置df['I']移动列中Time=21的最后两个值,以便拥有

   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

我尝试了以下

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

1 个答案:

答案 0 :(得分:3)

没有特殊的熊猫方式,但是您可以这样做:

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