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

问题描述 投票:0回答:1

我有一个数据帧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
python pandas
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.