6

I have a dataframe with 25 columns and an array([ 2, 4, 8, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 23], dtype=int64). I want to choose some specific columns from the dataframe whose indices are given by the elements of the array and store them in a new dataframe(say df1). So for example,the new dataframe, will have the 2nd, 4th,....23rd column of the original data frame.

DevanshuMishra
  • 89
  • 1
  • 2
  • 6

1 Answers1

3

You can use iloc to accomplish this. For example:

import pandas as pd

df = pd.DataFrame(
    [np.random.rand(5),np.random.rand(5), np.random.rand(5), np.random.rand(5)]
)

df.iloc[:,[1,3]]

Which outputs:

    1           3
0   0.883848    0.409460
1   0.537549    0.426643
2   0.825185    0.361043
3   0.039343    0.674435

You may see older answers suggesting .ix (such as the answer in this question that I adapted this from) however, that has been deprecated.

Zev
  • 3,423
  • 1
  • 20
  • 41