在同一 Pandas 数据框中交换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46890972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:40:43  来源:igfitidea点击:

Swapping rows within the same pandas dataframe

pythonpandasdataframerowsswap

提问by Zac

I'm trying to swap the rows within the same DataFrame in pandas.

我正在尝试在 Pandas 中交换同一个 DataFrame 中的行。

I've tried running

我试过跑步

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

but I just end up with both the rows showing the values for the second row (3,4).

但我最终得到的两行都显示了第二行(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?

即使变量 b 和 c 现在都分配给 3 和 4,即使我没有再次分配它们。难道我做错了什么?

回答by Bharath

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.

使用临时变量来存储值.copy(),因为您在链上分配值时正在更改值,即除非您使用复制,否则数据将直接更改。

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

回答by Leonardo Nunes

In this way, it can be extrapolated to more complex situations:

通过这种方式,它可以外推到更复杂的情况:

    a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
    rows = a.index.tolist()
    rows = rows[-1:]+rows[:-1]
    a=a.loc[rows]