在同一个pandas数据帧中交换行

问题描述 投票:6回答:2

我正在尝试在pandas中交换相同DataFrame中的行。

我试过跑步

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)。

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

python pandas dataframe rows swap
2个回答
7
投票

使用临时变量来存储使用.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

或者你可以直接使用副本

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

1
投票

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

    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]
© www.soinside.com 2019 - 2024. All rights reserved.