0 votes
1 view
in Machine Learning by (7.3k points)

I have data in different columns but I don't know how to extract it to save it in another variable.

index a b c

1 2 3 4

2 3 4 5

How do I select 'a', 'b' and save it into df1?

I tried

df1 = df['a':'b']

df1 = df.ix[:, 'a':'b']

None seem to work.

1 Answer

0 votes
by (17.8k points)

In pandas, you can select multiple columns by their name, but the column name gets stored as a list of the list that means a dictionary. It means you should use [ [ ] ] to pass the selected name of columns. This method df[['a','b']] produces a copy.

For example:

df1 = df[['a','b']]

You can also use ‘.iloc’ method to access the list by column name. It is efficient to access the column by the index number of a column name.

For example:

df1 = df.iloc[:,0:2]

Hope this answer helps.

...