pandas 反转列的顺序,而不更改列标签panda dataframe

nfg76nw0  于 2023-03-11  发布在  其他
关注(0)|答案(3)|浏览(160)

我需要反转我的Pandas Dataframe 的顺序。但使用以下代码:

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df = df.iloc[:, ::-1]

还反转列标签的顺序。如何仅反转数据并维护列标签?我希望得到:

A  B  C
0  7  4  1
1  8  5  2
2  9  6  3
mitkmikd

mitkmikd1#

如果大型 Dataframe 和性能很重要,则由构造函数分配给新的 Dataframe :

df = pd.DataFrame(np.random.randint(10, size=(1000,1000))).add_prefix('col')
# print (df)
In [108]: %timeit df[:] = df.values[:, ::-1]
5.19 ms ± 555 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [109]: %timeit df[:] = df.iloc[:, ::-1].to_numpy()
5.34 ms ± 288 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [110]: %timeit df.iloc[:, ::-1].set_axis(df.columns, axis=1)
2.42 ms ± 357 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [111]: %timeit pd.DataFrame(df.iloc[:, ::-1].to_numpy(), index=df.index,columns=df.columns)
102 µs ± 3.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [112]: %timeit pd.DataFrame(df.to_numpy()[:, ::-1], index=df.index, columns=df.columns)
43.7 µs ± 240 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
fjaof16o

fjaof16o2#

最短分配:

df[:] = df.values[:, ::-1]
A  B  C
0  7  4  1
1  8  5  2
2  9  6  3
u3r8eeie

u3r8eeie3#

要在位修改,请用途:

df[:] = df.iloc[:, ::-1].to_numpy()

或者,对于新对象:

out = df.iloc[:, ::-1].set_axis(df.columns, axis=1)

相关问题