Zac*_*Zac 6 python swap rows dataframe pandas
我正在尝试在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
Run Code Online (Sandbox Code Playgroud)
但我最后得到的两行显示第二行的值(3,4).
即使变量b和c现在都分配给3和4,即使我没有再次分配它们.难道我做错了什么?
使用临时变量来存储值.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
Run Code Online (Sandbox Code Playgroud)
或者你可以直接使用副本
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
Run Code Online (Sandbox Code Playgroud)
小智 5
通过这种方式,可以推断出更复杂的情况:
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
rows = a.index.to_list()
# Move the last row to the first index
rows = rows[-1:]+rows[:-1]
a=a.loc[rows]
Run Code Online (Sandbox Code Playgroud)