在同一 pandas 数据框中交换行
Swapping rows within the same pandas dataframe
我正在尝试交换 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,尽管我没有再次赋值它们。我做错了什么吗?
使用临时变量来存储使用 .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
或者直接复制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
这样,就可以推导出更复杂的情况:
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]
接受的答案没有更改索引名称。
如果您只想更改行的顺序,您应该使用 dataframe.reindex(arraylike)
。请注意索引已更改。
df = pd.DataFrame(data = [[1,2],[4,5],[6,7]], index=['a','b','c'], columns = ['A', 'B'])
df
df.reindex(['a','c','b'])
我正在尝试交换 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,尽管我没有再次赋值它们。我做错了什么吗?
使用临时变量来存储使用 .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
或者直接复制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
这样,就可以推导出更复杂的情况:
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]
接受的答案没有更改索引名称。
如果您只想更改行的顺序,您应该使用 dataframe.reindex(arraylike)
。请注意索引已更改。
df = pd.DataFrame(data = [[1,2],[4,5],[6,7]], index=['a','b','c'], columns = ['A', 'B'])
df
df.reindex(['a','c','b'])