Python: Extract different columns and assign to a new dataframe

Question:

I have this df:

A  B  C  D
1  2  3  4

I want to extract columns 0:1 and 3rd one

But first thought would be:

X = DS.iloc[:, 0:1:3].values

But, this approach does not work

Asked By: Another.Chemist

||

Answers:

If really you need to work with ranges, use numpy.r_ to combine them:

out = df.iloc[:, np.r_[0:2,3]]

If you know the columns, be explicit:

out = df[['A', 'B', 'D']]

Output:

   A  B  D
0  1  2  4
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.