[英]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.