简体   繁体   English

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

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

I have a dataframe df 我有一个数据框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 我想从位置Time=21列中的df['I']的最后两个值,以便

   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: 没有特殊的Pandas方式,但是您可以这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一些单元格值从 Pandas DF 中的 2 列移动到另一个新列? - How do I move some cell values from 2 columns in Pandas DF to another new column? Python:如何将数组中的值从某个位置移动到另一个位置? - Python: how to move values in an array from some position to another? 将某些 pandas dataframe 列值从一列移到另一列,并将旧的 position 替换为 Nan - Move certain pandas dataframe column values from one column to another and replace old position with Nan Pandas - 将一列的值移动到另一列下 - Pandas - move values of a column under another column 如何在大熊猫不相等的值上将数据从一列移动到另一列? - How do i move data from one column to another on values that aren't equal in pandas? 如何基于与熊猫匹配的列值将数据从一个数据帧移动到另一个数据帧? - How to move data from one dataframe to another based on matching column values with pandas? 用一些相同的值从另一个中减去一个pandas datetime列 - Subtracting one pandas datetime column from another with some identical values 如何在 python / pandas 中将一些值从一列转移到另一列? [等候接听] - How to shift some values from one column to another in python / pandas? [on hold] 如何根据出现在另一列中满足某些条件的这些行值从一列中选择熊猫中的行值 - How to select row values in pandas from one column based on these row values satisfying some condition in another column everywhere they appear 如何通过比较 Pandas 中另一列的值来填充列中的值 - How to fill values in column by comparison values from another column in Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM