在相同的 pandas 数据框中交换行 [英] Swapping rows within the same pandas dataframe
本文介绍了在相同的 pandas 数据框中交换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在熊猫中交换同一DataFrame中的行.
I'm trying to swap the rows within the same DataFrame in pandas.
我尝试跑步
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0], a.iloc[1]
a.iloc[0], a.iloc[1] = c, b
但是我最后两行都显示了第二行(3,4)的值.
but I just end up with both the rows showing the values for the second row (3,4).
即使变量b和c现在都已分配给3和4,即使我没有再次分配它们.我在做错什么吗?
Even the variables b and c are now both assigned to 3 and 4 even though I did not assign them again. Am I doing something wrong?
推荐答案
使用临时变量使用.copy()
存储值,因为在链上分配值时正在更改值,即除非使用复制,否则数据将是直接更改.
Use a temporary varaible to store the value using .copy()
, because you are changing the values while assigning them on chain i.e. Unless you use copy the data will be changed directly.
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0], a.iloc[1]
temp = a.iloc[0].copy()
a.iloc[0] = c
a.iloc[1] = temp
或者您可以直接使用类似的副本
Or you can directly use copy like
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0].copy(), a.iloc[1].copy()
a.iloc[0],a.iloc[1] = c,b
这篇关于在相同的 pandas 数据框中交换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文