Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (19k 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 (33.1k 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.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...