Selecting multiple columns in a pandas dataframe

Machine Learning

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.



You can slice the column names with the help of .loc indexer.

df.loc[:, 'a':'b']


You won't be able to slice the column names.

If you know which variables you want to slice from context, you can return a view of them.

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


If you want to unleash your potential in this competitive field, please visit the Machine Learning course page for more information, where you can find the Machine Learning tutorials and Machine Learning frequently asked interview questions and answers as well.


This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.