Getting the Required Column Indexes from an array and adding those columns to a dataframe

I have a dataframe like this:

A B C D 
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

And I am writing a piece of code to identify what are the column indexes I need.

RequiredColumns = (skb.get_support(indices=True))
Out[64]: array([ 0,  1], dtype=int64)

I am going to take only those columns and add it to the new dataframe.

For that - I wrote this piece of code

FeatureSelected_DataFrame = pd.DataFrame()

for i in RequiredColumns:
    ColIndex = i
    ReqColumn = X[[i]]
    FeatureSelected_DataFrame = FeatureSelected_DataFrame.append(ReqColumn)

But this is the output I am getting: FeatureSelected_DataFrame

A   B
1   NaN
1   NaN
NaN 2
NaN 2

My expected output was -

A B  
1 2 
1 2 

Upvotes: 2

Views: 37

Answers (1)

jezrael
jezrael

Reputation: 862441

I think you can append columns selected by positions by iloc to list and then concat:

L = []
RequiredColumns = np.array([0,1])
for i in RequiredColumns:
    ReqColumn = X.iloc[:, i]
    L.append(ReqColumn)

FeatureSelected_DataFrame = pd.concat(L, axis=1)
print (FeatureSelected_DataFrame)
   A  B
0  1  2
1  1  2
2  1  2
3  1  2

Better non loop solution is:

RequiredColumns = np.array([0,1])
df = X.iloc[:, RequiredColumns]
print (df)
   A  B
0  1  2
1  1  2
2  1  2
3  1  2

Upvotes: 2

Related Questions