子集pandas df使用列索引切片的串联

时间:2017-09-07 17:39:55

标签: python pandas dataframe subset indices

我有一个大型数据框,我试图仅使用列索引进行子集化。我使用以下代码:

  File "<ipython-input-44-3108b602b220>", line 1
  df = df.ix[:, [3,21:28,30:34,36:57,61:64,67:]]
                     ^
  SyntaxError: invalid syntax

代码非常自我解释。我试图通过保持列3,21到28等来对df进行子集化。但是,我收到以下错误:

ContentResolver

我错过了什么?

1 个答案:

答案 0 :(得分:0)

使用numpy.r_[...]

df = df.iloc[:, np.r_[3,21:28,30:34,36:57,61:64,67:df.shape[1]]]

演示:

In [39]: df = pd.DataFrame(np.random.randint(5, size=(2, 100)))

In [40]: df
Out[40]:
   0   1   2   3   4   5   6   7   8   9  ...  90  91  92  93  94  95  96  97  98  99
0   3   1   0   3   2   4   1   2   1   3 ...   2   1   4   2   1   2   1   3   3   4
1   0   2   4   1   1   1   0   0   3   4 ...   4   4   0   3   2   3   0   2   0   1

[2 rows x 100 columns]

In [41]: df.iloc[:, np.r_[3,21:28,30:34,36:57,61:64,67:df.shape[1]]]
Out[41]:
   3   21  22  23  24  25  26  27  30  31 ...  90  91  92  93  94  95  96  97  98  99
0   3   4   1   2   0   3   0   3   2   2 ...   2   1   4   2   1   2   1   3   3   4
1   1   1   0   2   1   4   4   4   1   3 ...   4   4   0   3   2   3   0   2   0   1

[2 rows x 69 columns]