颠倒数据框列的顺序

时间:2019-01-21 15:11:10

标签: python python-3.x pandas

const loader = new PIXI.loaders.Loader(); loader.add('fffforward', 'assets/fonts/fffforward.TTF'); loader.load((loader, resources) => { PointsTopText = new Text( "P1: " + PointsTop, {fontFamily: 'FFFForward', fontSize: 32, fill: 'white'} ); World.addChild(PointsTopText); }); 是按列反转df.reindex(columns=reversed(df.columns))的最快方法吗?

2 个答案:

答案 0 :(得分:1)

一个想法-将DataFrame.iloc与索引一起使用:

df = df.iloc[:, ::-1]

性能

np.random.seed(234)

df = pd.DataFrame(np.random.randint(10, size=(3, 10000))).rename(columns=str)
#print (df)

In [225]: %timeit df.reindex(columns=reversed(df.columns))
7.32 ms ± 166 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [226]: %timeit df.iloc[:, ::-1]
132 µs ± 6.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

#vdkotian solution
In [227]: %timeit df[df.columns[::-1]]
2.84 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

答案 1 :(得分:0)

只需尝试样本数据集。

sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa
3           4.6          3.1           1.5          0.2  setosa
4           5.0          3.6           1.4          0.2  setosa
5           5.4          3.9           1.7          0.4  setosa
6           4.6          3.4           1.4          0.3  setosa
7           5.0          3.4           1.5          0.2  setosa
8           4.4          2.9           1.4          0.2  setosa
9           4.9          3.1           1.5          0.1  setosa

>>> df[df.columns[::-1]]


species  petal_width  petal_length  sepal_width  sepal_length
0  setosa          0.2           1.4          3.5           5.1
1  setosa          0.2           1.4          3.0           4.9
2  setosa          0.2           1.3          3.2           4.7
3  setosa          0.2           1.5          3.1           4.6
4  setosa          0.2           1.4          3.6           5.0
5  setosa          0.4           1.7          3.9           5.4
6  setosa          0.3           1.4          3.4           4.6
7  setosa          0.2           1.5          3.4           5.0
8  setosa          0.2           1.4          2.9           4.4
9  setosa          0.1           1.5          3.1           4.9

df.column [::-1]按照列的顺序反转数据帧的顺序,而df [..]重新索引它。

使用iloc索引器可以更简洁地实现同一目的:

df.iloc[:, ::-1]

第一个:表示“占据所有行”,::-1表示后退各列。

供参考,请参见link https://stackoverflow.com/questions/27817718/reverse-dataframe-column-order