在一个巨大的熊猫数据帧中将几列放在前面



我有一个有 1000 列的熊猫系列。 将其中三列放在前面(任意三列(的最简单方法是什么,假设第 10、30 和 1000 列,其余列为它们让路。

我知道我能做到:

Df = Df.iloc[:,[10, 30, 1000]]

但是,这只给了我三列

Columns 
10    30   50

但是我想要这样的输出:

10    30   1000   1      2       3      4     5     6     7      8     999

也就是说,我想将三列移到前面,并将其余的列移回以腾出空间。最简单的方法是什么?因为我需要在数据库中经常这样做。

问候

以下是将sortedkey一起使用的一种方法:

first = [10, 30, 1000]
df[sorted(df.columns, key=lambda x: x not in first)]

例:

df = pd.DataFrame(columns = list(range(10)))
first = [2,3,9]
print(df[sorted(df.columns, key=lambda x: x not in first)].columns)
# Int64Index([2, 3, 9, 0, 1, 4, 5, 6, 7, 8], dtype='int64')

这是使用numpy.r_Index.difference的另一种方法:

import numpy as np
# Setup
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10, 7))
cols = [2, 5, 6]
df[np.r_[cols, df.columns.difference(cols)]]

[出]

          2         5         6         0         1         3         4
0  0.978738 -0.977278  0.950088  1.764052  0.400157  2.240893  1.867558
1  0.410599  0.761038  0.121675 -0.151357 -0.103219  0.144044  1.454274
2  1.494079 -0.854096 -2.552990  0.443863  0.333674 -0.205158  0.313068
3 -0.742165  0.045759 -0.187184  0.653619  0.864436  2.269755 -1.454366
4  0.154947 -1.980796 -0.347912  1.532779  1.469359  0.378163 -0.887786
5  1.202380 -1.048553 -1.420018  0.156349  1.230291 -0.387327 -0.302303
6 -0.509652  0.777490 -1.613898 -1.706270  1.950775 -0.438074 -1.252795
7  0.386902 -0.028182  0.428332 -0.212740 -0.895467 -0.510805 -1.180632
8 -0.634322 -0.359553 -0.813146  0.066517  0.302472 -0.362741 -0.672460
9 -0.401781 -0.907298  0.051945 -1.726283  0.177426 -1.630198  0.462782

试试这个:

cols = df.columns.tolist()
# select columns in order you want
cols = list(cols[10]) + list(cols[30]) + list(cols[1000]) + cols[:]
# remove duplicated columns
cols = list(dict.fromkeys(cols)) 
df[cols]

最新更新